56 lines
1.2 KiB
C
56 lines
1.2 KiB
C
|
#include <stdio.h>
|
||
|
#include <arpa/inet.h>
|
||
|
#include <sys/socket.h>
|
||
|
#include <netinet/in.h> // 地址结构
|
||
|
#include <unistd.h>
|
||
|
#include <string.h>
|
||
|
|
||
|
int main(int argc, char const *argv[])
|
||
|
{
|
||
|
// 1. 创建套接字
|
||
|
int sfd = socket(AF_INET, SOCK_DGRAM, 0);
|
||
|
if (sfd < 0)
|
||
|
{
|
||
|
perror("socket");
|
||
|
return -1;
|
||
|
}
|
||
|
|
||
|
// 2. 创建发送目标的ip地址和端口号
|
||
|
struct sockaddr_in addr;
|
||
|
bzero(&addr, sizeof(addr)); // 初始化置零
|
||
|
addr.sin_family = AF_INET;
|
||
|
addr.sin_port = htons(8000);
|
||
|
inet_pton(AF_INET, "192.168.31.1", &addr.sin_addr.s_addr);
|
||
|
|
||
|
int n = 1;
|
||
|
|
||
|
// 3. 创建发送的数据
|
||
|
while (1)
|
||
|
{
|
||
|
char buf[128] = "";
|
||
|
scanf("%s", buf);
|
||
|
if (strncmp(buf, "exit", 4) == 0)
|
||
|
{
|
||
|
break;
|
||
|
}
|
||
|
// sprintf(buf, "this is : %lld\n", (n++ * ++n));
|
||
|
|
||
|
// 4. 发送一次 udp 数据
|
||
|
ssize_t n = sendto(sfd, buf, strlen(buf), 0, (struct sockaddr *)&addr, sizeof(addr));
|
||
|
if (n > 0)
|
||
|
{
|
||
|
printf("%s: 发送 udp 数据成功\n", buf);
|
||
|
}
|
||
|
else
|
||
|
{
|
||
|
printf("%s: 发送失败\n", buf);
|
||
|
perror("sendto");
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// 5. 关闭 socket
|
||
|
close(sfd);
|
||
|
|
||
|
return 0;
|
||
|
}
|