服务端代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>
int main(int argc, char *argv[])
{
int sockfd;
struct sockaddr_in clt_addr, my_addr;
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("socket");
return -1;
}
bzero(&my_addr, sizeof(my_addr));
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(atoi(argv[2]));
inet_pton(AF_INET, argv[1], &my_addr.sin_addr);
if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(my_addr)) < 0)
{
perror("bind");
return -1;
}
/*
bzero(&clt_addr, sizeof(clt_addr));
clt_addr.sin_family = AF_INET;
clt_addr.sin_port = htons(atoi(argv[4]));
inet_pton(AF_INET, argv[3], &clt_addr.sin_addr);
//服务端可以调用connect与客户端进行绑定,这样服务端只接收该客户端的数据,recvfrom最后两个参数可设为空
if (connect(sockfd, (struct sockaddr *)&clt_addr, sizeof(clt_addr)) < 0)
{
perror("connect");
return -1;
}
*/
int len = 0;
char buffer[1500];
socklen_t addr_len = sizeof(clt_addr);
while ((len = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&clt_addr, &addr_len)) > 0)
{
buffer[len-1] = '\0';
printf("%s\n", buffer);
}
close(sockfd);
return 0;
}
客户端代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
int sockfd;
struct sockaddr_in my_addr, srv_addr;
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("socket");
return -1;
}
bzero(&srv_addr, sizeof(srv_addr));
srv_addr.sin_family = AF_INET;
srv_addr.sin_port = htons(atoi(argv[2]));
inet_pton(AF_INET, argv[1], &srv_addr.sin_addr);
/*
bzero(&my_addr, sizeof(my_addr));
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(atoi(argv[4]));
inet_pton(AF_INET, argv[3], &srv_addr.sin_addr);
//如果服务端connect了客户端的ip和port,客户端需要调用bind绑定
if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(my_addr)) < 0)
{
perror("bind");
return -1;
}
//客户端可以调用connect与服务端进行绑定,sendto最后两个参数可设为空
if (connect(sockfd, (struct sockaddr *)&srv_addr, sizeof(srv_addr)))
{
perror("connect");
return -1;
}
*/
int len = 0;
char *buffer = "hello server!";
while (1)
{
sendto(sockfd, buffer, strlen(buffer), 0, (struct sockaddr *)&srv_addr, sizeof(srv_addr));
sleep(5);
}
close(sockfd);
return 0;
}