实例:
server.cpp
#include <iostream> #include <strings.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> using namespace std; int main() { int sockfd; struct sockaddr_in saddr; int r; char recvline[1025]; struct sockaddr_in presaddr; socklen_t len; sockfd = socket(AF_INET, SOCK_DGRAM, 0); bzero(&saddr, sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = htonl(INADDR_ANY); saddr.sin_port = htons(9999); bind(sockfd, (struct sockaddr*)&saddr, sizeof(saddr)); while (1) { r = recvfrom(sockfd, recvline, sizeof(recvline), 0 , (struct sockaddr*)&presaddr, &len); if (r <= 0) { perror(""); exit(-1); } recvline[r] = 0; cout <<"recvfrom "<< inet_ntoa(presaddr.sin_addr) <<" " << recvline << endl; } return 0; }
client.cpp
#include <iostream> #include <strings.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> using namespace std; int main() { int sockfd; struct sockaddr_in des_addr; int r; char sendline[1024] = {"Hello"}; const int on = 1; sockfd = socket(AF_INET, SOCK_DGRAM, 0); setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)); //设置套接字选项 bzero(&des_addr, sizeof(des_addr)); des_addr.sin_family = AF_INET; des_addr.sin_addr.s_addr = inet_addr("192.168.199.255"); //广播地址 des_addr.sin_port = htons(9999); r = sendto(sockfd, sendline, strlen(sendline), 0, (struct sockaddr*)&des_addr, sizeof(des_addr)); if (r <= 0) { perror(""); exit(-1); } cout << "finish" << endl; return 0; }
原文:http://blog.csdn.net/aspnet_lyc/article/details/34444111