#define SERVICE_IPADDR "192.168.1.12"
#define SERVER_PORT 30000
struct sockaddr_in server_addr;
int tolen;
int server_fd = -1;
if((server_fd = socket(AF_INET, SOCK_DGRAM, 0)) >= 0) {
printf("server_fd=%d\r\n", server_fd);
}
else {
printf("socket error\n");
goto exit;
}
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
server_addr.sin_addr.s_addr = inet_addr(SERVICE_IPADDR);
tolen = sizeof(struct sockaddr_in);
/*
if(bind(server_fd, (struct sockaddr *) &server_addr, sizeof(server_addr)) != 0) {
printf("bind error\r\n");
goto exit;
}
*/
如国取消注释掉bind那段代码,相当于udp处于client模式,发送端口系统随机分配,目的端口为SERVER_PORT,只有当本机先发送数据,对端才能发送数据过来。
如果执行bind段代码,udp处于server模式,接收端口为SERVER_PORT,目的端口随机分配,对端先发送数据,本机再发送数据。