udp.cc
来自「达内IT培训Unix C++第一天源码(共四天) 是入门Unix 下C++编程」· CC 代码 · 共 60 行
CC
60 行
#include <iostream>using namespace std;#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#include <unistd.h>#include <fcntl.h>#include <cstring>int main(){ short port; cout << "input your port:"; cin >> port; sockaddr_in si; char ip[100]; char buf[1000]; socklen_t len=sizeof(si); char cmd; int s = socket(AF_INET, SOCK_DGRAM, 0); if(s<0){ cout << "socket error!" << endl; return -1; } si.sin_family = AF_INET; si.sin_addr.s_addr=htonl(INADDR_ANY); si.sin_port = htons(port); if(bind(s,(sockaddr*)&si,len)<0){ cout << "bind error!" << endl; return -1; } for(;;){ cout << "r/s/q:"; cin >> cmd; if(cmd=='q') break; if(cmd=='r'){ int n=recvfrom(s, buf, 1000, 0, (sockaddr*)&si, &len); if(n<0) break; buf[n] = '\0'; inet_ntop(AF_INET,&si.sin_addr,ip,100); port = ntohs(si.sin_port); cout << ip << '@' << port << ':' << buf << endl; } else if(cmd=='s'){ cout << "input ip, port and message:"; cin >> ip >> port; cin.getline(buf, 1000); si.sin_port = htons(port); inet_pton(AF_INET,ip,&si.sin_addr); sendto(s,buf,strlen(buf),0,(sockaddr*)&si,len); } else{ cout << "invalid command!" << endl; } } close(s);}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?