47 lines
1.2 KiB
C
47 lines
1.2 KiB
C
|
// 编写一个UDP客户端程序, 向服务器发送一个字符串, 并接收服务器返回的字符串并打印出来。
|
||
|
#include <stdio.h>
|
||
|
#include <sys/socket.h>
|
||
|
#include <netinet/in.h>
|
||
|
#include <arpa/inet.h>
|
||
|
#include <unistd.h>
|
||
|
#include <string.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 = inet_addr("127.0.0.1"); // 指定服务器地址
|
||
|
|
||
|
// 创建发送的数据
|
||
|
char buf[128] = "this msg is from client";
|
||
|
|
||
|
// 发送 udp 数据
|
||
|
ssize_t n = sendto(sock_fd, buf, strlen(buf), 0, (struct sockaddr *)&addr, sizeof(addr)); // 将 buf 数据发送给服务器
|
||
|
if (n > 0)
|
||
|
{
|
||
|
perror("发送成功\n");
|
||
|
}
|
||
|
|
||
|
socklen_t addrlen = sizeof(addr);
|
||
|
|
||
|
ssize_t recvlen = recvfrom(sock_fd, buf, 128, 0, (struct sockaddr *)&addr, &addrlen); // 从服务器获取数据到 buf
|
||
|
if (recvlen < 0)
|
||
|
{
|
||
|
perror("recvfrom");
|
||
|
return 1;
|
||
|
}
|
||
|
|
||
|
printf("从服务器获取的数据为 %s\n", buf);
|
||
|
|
||
|
return 0;
|
||
|
}
|