文章目录
- 基本流程
- recvfrom和sendto函数
- 试着用用
基本流程
客户端
- 创建套接字socket()
- 填充服务器网路信息结构体
- 通信recvfrom()/sendto()
服务器
- 创建套接字
- 填充服务器网路信息结构体
- 将套接字与服务器网络信息结构体绑定bind()
- 进行通信recvfrom()/sendto()
recvfrom和sendto函数
函数原型
#include <sys/socket.h>
ssize_t recvfrom(int sockfd, void *buff, ssize_t nbytes, int flags, struct sockaddr *from, socklen_t *addrlen);
ssize_t sendto(int sockfd, const void *buff, size_t nbytes, int flags, const struct sockaddr *to, socklen_t addrlen);
参数
sockfd
:描述符
buff
:指向读入或写出缓冲区的指针
nbytes
:读入或写出的字节数
flags
:标志位,0阻塞,MSG_DONTWAIT非阻塞
from
:指向一个由该函数返回时填写数据报发送者的协议地址的套接字地址结构
to
:指向含有数据报接收者的协议地址
addrlen
:记录地址长度
试着用用
服务器
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>int main(int argc, char *argv[])
{int sockfd;struct sockaddr_in serveraddr, clientaddr;socklen_t addrlen = sizeof(serveraddr);char buf[100] = {0};sockfd = socket(AF_INET, SOCK_DGRAM, 0);serveraddr.sin_family = AF_INET;serveraddr.sin_port = htons(atoi(argv[2]));serveraddr.sin_addr.s_addr = inet_addr(argv[1]);bind(sockfd, (struct sockaddr *)&serveraddr, addrlen);while(1){if(recvfrom(sockfd, buf, 100, 0, (struct sockaddr*)&clientaddr, &addrlen) == -1){printf("recvfrom error\n");}printf("%s-%d: %s\n", inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port), buf);strcat(buf, "hi!");if(sendto(sockfd, buf, 100, 0, (struct sockaddr *)&clientaddr, addrlen) == -1){printf("sendto error");}}return 0;
}
客户端
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>int main(int argc, char *argv[])
{int sockfd;struct sockaddr_in serveraddr;socklen_t addrlen = sizeof(serveraddr);serveraddr.sin_family = AF_INET;serveraddr.sin_port = htons(atoi(argv[2]));serveraddr.sin_addr.s_addr = inet_addr(argv[1]);sockfd = socket(AF_INET, SOCK_DGRAM, 0);char buf[100];while(1){fgets(buf, 100, stdin);buf[strlen(buf)-1] = '\0';sendto(sockfd, buf, 100, 0, (struct sockaddr*)&serveraddr, addrlen);memset(buf, 0, sizeof(buf));recvfrom(sockfd, buf, 100, 0, (struct sockaddr*)&serveraddr, &addrlen);printf("server: %s\n", buf);}return 0;
}