43 lines
997 B
C
43 lines
997 B
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, "10.35.188.66", &addr.sin_addr.s_addr);
|
||
|
|
||
|
// 3. 创建发送的数据
|
||
|
char *buf = "hi, udp server: disen hh";
|
||
|
|
||
|
// 4. 发送一次 udp 数据
|
||
|
ssize_t n = sendto(sfd, buf, strlen(buf), 0, (struct sockaddr *)&addr, sizeof(addr));
|
||
|
if (n > 0)
|
||
|
{
|
||
|
printf("发送 udp 数据成功\n");
|
||
|
}else{
|
||
|
printf("发送失败\n");
|
||
|
perror("sendto");
|
||
|
}
|
||
|
|
||
|
// 5. 关闭 socket
|
||
|
close(sfd);
|
||
|
|
||
|
return 0;
|
||
|
}
|