网络编程Socket UDP

时间:2022-09-23 14:40:00

图表流程

网络编程Socket UDP

linux udp测试代码

//server.c
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <sys/socket.h>
#include <sys/unistd.h>
#include <arpa/inet.h> #define PORT 8999
#define MAXSIZE 4096 int main(int argc, char *argv[])
{
int sockfd, addr_len;
struct sockaddr_in serv_addr, clnt_addr;
char recvmsg[MAXSIZE], sendmsg[MAXSIZE]; sockfd = socket(AF_INET, SOCK_DGRAM, );
if (sockfd < ) {
perror("socket error");
return -;
} serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
serv_addr.sin_addr.s_addr = INADDR_ANY;
memset(&(serv_addr.sin_zero), ,); if (bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr)) < ) {
perror("bind err");
return -;
} while() {
memset(sendmsg, , MAXSIZE);
memset(recvmsg, , MAXSIZE);
addr_len = sizeof(struct sockaddr);
/* 所谓的非阻塞I/O */
if (recvfrom(sockfd, recvmsg, MAXSIZE, , (struct sockaddr *)&clnt_addr, &addr_len) < ) {
perror("recv");
continue;
} printf("begin to accept\n");
printf("recv from %s : %s\n", inet_ntoa(clnt_addr.sin_addr), recvmsg);
strcpy(sendmsg, "who are you ?? Let me cc!");
sendto(sockfd, sendmsg, strlen(sendmsg) + , , (struct sockaddr *)&clnt_addr, addr_len);
} return ;
}
//client.c
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <sys/socket.h>
#include <sys/unistd.h>
#include <arpa/inet.h> #define PORT 8999
#define DESIP "192.168.23.109"
#define MAXSIZE 4096 int main(int argc, char *argv[])
{
int sockfd, addr_len;
struct sockaddr_in des_addr;
char sendmsg[MAXSIZE], recvmsg[MAXSIZE]; sockfd = socket(AF_INET, SOCK_DGRAM, );
if (sockfd < ) {
perror("socket error");
return -;
} des_addr.sin_family = AF_INET;
des_addr.sin_port = htons(PORT);
des_addr.sin_addr.s_addr = inet_addr(DESIP);
//bzero(&(des_addr.sin_zero), 8);
memset(&(des_addr.sin_zero), ,);
while () {
memset(recvmsg, , MAXSIZE);
memset(sendmsg, , MAXSIZE);
printf("input:\n");
gets(sendmsg);
if (strcmp(sendmsg, "quit") == ) {
close(sockfd);
printf("close connection\n");
return -;
}
if (sendto(sockfd, sendmsg, strlen(sendmsg) + , , (struct sockaddr *)&des_addr, sizeof(struct sockaddr)) < ) {
perror("sendto");
continue;
}
printf("send ok...\n"); while () {/* 所谓的非阻塞I/O */
addr_len = sizeof(struct sockaddr);
if (recvfrom(sockfd, recvmsg, MAXSIZE, , (struct sockaddr *)&des_addr, &addr_len) < ) {
continue;
}
printf("recv from %s : %s\n", inet_ntoa(des_addr.sin_addr), recvmsg);
break;
}
} return ;
}

参考资料:

Linux的Socket编程详解

Linux Socket编程(不限Linux)