linux下udp编程简单示例

#include <iostream> using namespace std; #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <unistd.h> int main() { sockaddr_in si; short port; socklen_t len=sizeof(si); int s = socket(AF_INET, SOCK_DGRAM,0); if(s<0) return -1; cout << "input port:"; cin >> port; si.sin_family = AF_INET; si.sin_port = htons(port); si.sin_addr.s_addr=htonl(INADDR_ANY); if(bind(s,(sockaddr*)&si,len)<0) return -1; for(;;){ char cmd; char msg[1000]; char ip[100]; cout << "r/s/q:"; cin >> cmd; if(cmd=='q') break; if(cmd=='r'){ int n=recvfrom(s, msg, 1000, 0, (sockaddr*)&si, &len); if(n<0) break; inet_ntop(AF_INET, &si.sin_addr, ip, 100); port = ntohs(si.sin_port); msg[n] = '/0'; cout << ip << '@' << port << ':' << msg << endl; } else if(cmd=='s'){ cout << "input ip and port:"; cin >> ip >> port; cout << "input msg:"; cin >> ws; cin.getline(msg, 1000); inet_pton(AF_INET,ip,&si.sin_addr); si.sin_port = htons(port); sendto(s, msg, strlen(msg), 0, (sockaddr*)&si, len); } else{ cout << "invalid command!/n"; cin.ignore(100, '/n'); } } close(s); }

无所谓服务器客户端:

1、socket

2、bind

3、收发

你可能感兴趣的:(linux下udp编程简单示例)