⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 udp.cc

📁 达内IT培训Unix C++第一天源码(共四天) 是入门Unix 下C++编程的好东西
💻 CC
字号:
#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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -