#include <stdio.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <netinet/in.h> int main(int argc, char const *argv[]) { // 1.创建套接字 int sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) { perror("sockfd"); return -1; } // 2.广播 int optval = 1; setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, (void *)&optval, sizeof(optval)); // 3.发送数据 struct sockaddr_in toaddr; toaddr.sin_family = AF_INET; toaddr.sin_port = htons(8000); toaddr.sin_addr.s_addr = htonl("10.9.42.225"); sendto(sockfd, "hello", strlen("hello"), 0, (struct sockaddr *)&toaddr, sizeof(toaddr)); // 4.关闭套接字 close(sockfd); return 0; }
标签:int,代码,C语言,广播,toaddr,sockfd,include,sin,optval From: https://www.cnblogs.com/mengyaoli/p/17900007.html