74 lines
2.1 KiB
C
74 lines
2.1 KiB
C
// b->服务端
|
|
#include <stdio.h>
|
|
#include <arpa/inet.h>
|
|
#include <netinet/in.h>
|
|
#include <unistd.h>
|
|
#include <string.h>
|
|
#include <sys/socket.h>
|
|
|
|
int main(int argc, char const *argv[])
|
|
{
|
|
int sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
|
|
if (sock_fd < 0)
|
|
{
|
|
perror("socket");
|
|
return -1;
|
|
}
|
|
|
|
struct sockaddr_in addr;
|
|
bzero(&addr, sizeof(addr));
|
|
addr.sin_family = AF_INET;
|
|
addr.sin_port = htons(8000);
|
|
addr.sin_addr.s_addr = htonl(INADDR_ANY);
|
|
|
|
if (bind(sock_fd, (struct sockaddr *)&addr, sizeof(addr)) != 0)
|
|
{
|
|
perror("bind");
|
|
}
|
|
else
|
|
{
|
|
printf("bind success\n");
|
|
|
|
struct sockaddr_in src_addr;
|
|
int n = 0; // 接收数的空间
|
|
socklen_t socklen = sizeof(src_addr);
|
|
while (1)
|
|
{
|
|
bzero(&src_addr, sizeof(src_addr));
|
|
|
|
// 接收数据,如果数据未到达,则会阻塞,直到数据到达为止
|
|
ssize_t len = recvfrom(sock_fd, &n, sizeof(n), 0, (struct sockaddr *)&src_addr, &socklen);
|
|
if (len < 0)
|
|
{
|
|
perror("recvfrom");
|
|
break;
|
|
}
|
|
|
|
char srcIP[INET_ADDRSTRLEN]; // 16
|
|
int port = ntohs(src_addr.sin_port); // 将网络字节序转化为本地字节序
|
|
inet_ntop(AF_INET, &src_addr.sin_addr.s_addr, srcIP, INET_ADDRSTRLEN); // 将网络数字转换为点分十进制 ip
|
|
|
|
printf("从 %s:%d 位置接收到的数字为(%lu Bytes): %d\n", srcIP, port, len, n);
|
|
|
|
|
|
char sendbuf[128] = "";
|
|
|
|
if (n == 1)
|
|
strcpy(sendbuf, "disen666");
|
|
else if (n == 2)
|
|
strcpy(sendbuf, "jack good");
|
|
else if (n == 3)
|
|
strcpy(sendbuf, "disen888");
|
|
else if (n == 4)
|
|
strcpy(sendbuf, "bye");
|
|
|
|
sendto(sock_fd, &sendbuf, strlen(sendbuf), 0, (struct sockaddr *)&src_addr, socklen);
|
|
printf("发送回去内容为 %s\n", sendbuf);
|
|
}
|
|
}
|
|
|
|
close(sock_fd);
|
|
|
|
return 0;
|
|
}
|