服务端
步骤:
1. 创建套接字
2. 绑定ip
3. 读取数据
#include <stdio.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <linux/in.h>
#define SRV_PORT 9999
int main(int argc, char *argv[])
{
int srv_fd;
int ret;
char buf[128];
srv_fd = socket(AF_INET, SOCK_DGRAM, 0);
if(srv_fd < 0)
{
perror("socket");
exit(1);
}
struct sockaddr_in self;
self.sin_family = AF_INET;
self.sin_port = htons(SRV_PORT);
self.sin_addr.s_addr = htonl(INADDR_ANY);
ret = bind(srv_fd, (const struct sockaddr *)&self, sizeof(self));
if(ret < 0)
{
perror("bind");
exit(1);
}
struct sockaddr_in info;
socklen_t len = sizeof(info);
while(1)
{
ret = recvfrom(srv_fd, buf, 128, 0, (struct sockaddr *)&info, &len);
if(ret < 0)
{
perror("read");
exit(1);
}
buf[ret] = '\0';
printf("from client %s (port %d) : %s\n", inet_ntoa(info.sin_addr), ntohs(info.sin_port), buf);
}
close(srv_fd);
return 0;
}
客户端
步骤:
1. 创建套接字
2. 发送信息
#include <stdio.h>
#include <string.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <linux/in.h>
#define SRV_PORT 9999
#define SRV_IP "192.168.7.5"
int main(int argc, char *argv[])
{
int ret;
int count = 5;
char wbuf[128];
if(argc < 2)
{
printf("usage : ./client serverip\n");
exit(1);
}
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if(fd < 0)
{
perror("socket");
exit(1);
}
struct sockaddr_in peer;
peer.sin_family = AF_INET;
peer.sin_port = htons(SRV_PORT);
inet_aton(argv[1], &peer.sin_addr);
while(1)
{
printf("dear, pls input your words : \n");
fgets(wbuf, 128, stdin);
ret = sendto(fd, wbuf, 128, 0, (struct sockaddr *)&peer, sizeof(peer));
if(ret < 0)
{
perror("sendto");
exit(1);
}
}
close(fd);
return 0;
}