客户端
//UDP 客户端
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <fcntl.h>
#define MAXLINE 4096
#define SERVER_PORT 8000
/* 这里的多有函数没有作出错判断 */
int main(int argc, char *argv[])
{
struct sockaddr_in serveraddr;
int confd;
char ipstr[] = "192.168.1.253";
char buf[MAXLINE];
ssize_t len;
if(argc < 2) {
printf("./client str\n");
exit(1);
}
//1.创建一个socket
confd = socket(AF_INET, SOCK_DGRAM, 0);
//2.初始化服务器地址
bzero(&serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
//"192.168.1.253"
inet_pton(AF_INET, ipstr, &serveraddr.sin_addr.s_addr);
serveraddr.sin_port = htons(SERVER_PORT);
//3.向服务器发送数据
sendto(confd, argv[1], strlen(argv[1]), 0, (struct sockaddr *)&serveraddr, sizeof(serveraddr));
len = recvfrom(confd, buf, sizeof(buf), 0, NULL, 0);
write(STDOUT_FILENO, buf, len);
close(confd);
//5.关闭socket
close(confd);
return 0;
}
服务端
//UDP 服务端
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <ctype.h>
#define SERVER_PORT 8000
#define MAXLINE 1500 //MTU 最大传输单元
int main(void)
{
int sockfd, i;
struct sockaddr_in serveraddr, clientaddr;
char buf[MAXLINE];
char ipstr[INET_ADDRSTRLEN]; //16 Bytes
socklen_t clientlen;
ssize_t len;
/* 构造用于UDP的套接字 */
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
bzero(&serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); //本地任意IP
// printf("%x\n", INADDR_ANY); //这个直为0
serveraddr.sin_port = htons(SERVER_PORT);
bind(sockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr));
while (1) {
clientlen = sizeof(clientaddr);
len = recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&clientaddr, &clientlen);
printf("client IP %s\tPORT %d\n", inet_ntop(AF_INET, &clientaddr.sin_addr.s_addr, ipstr, sizeof(ipstr)), ntohs(clientaddr.sin_port));
i = 0;
while (i < len) {
buf[i] = toupper(buf[i]);
i++;
}
//buf[i] = '\0';
sendto(sockfd, buf, strlen(buf), 0, (struct sockaddr *)&clientaddr, sizeof(clientaddr));
}
close(sockfd);
return 0;
}