目录
一.socket创建通信的套接字
二.IPv4地址结构
三.通用地址结构
四. 两种地址结构的使用场合
五.sendto发送数据
六.bind固定地址信息编辑
七.recvfrom接受UDP的消息编辑
一.socket创建通信的套接字
二.IPv4地址结构
三.通用地址结构
四. 两种地址结构的使用场合
五.sendto发送数据
六.bind固定地址信息
代码实例:
#include <cstdio>
#include<iostream>
#include<string.h> //memset
#include<arpa/inet.h> //htos
#include<sys/socket.h> //socket
#include<netinet/in.h> //struct sockaddr
#include<unistd.h> //closevoid pra() {int sock = socket(AF_INET, SOCK_STREAM, 0);if (sock != -1) {//绑定本地IP和端口struct sockaddr_in my_addr;memset(&my_addr , 0, sizeof my_addr);my_addr.sin_family = AF_INET;my_addr.sin_port = htons(9000);my_addr.sin_addr.s_addr = INADDR_ANY; //绑定本地所有ipbind(sock, (struct sockaddr*)&my_addr, sizeof my_addr);//设置目的地址结构char* serv_ip = "196.168.233.13"; //声明serve IP地址struct sockaddr_in ser_addr; //定义IPv4地址结构,存放服务器的地址信息(目的主机)memset(&ser_addr, 0, sizeof ser_addr); //结构体变量addr所有成员初始化为0ser_addr.sin_family = AF_INET; //指定地址族//32位Ipv4地址omojokppi//inet_addr();inet_pton(AF_INET, serv_ip, &ser_addr.sin_addr.s_addr);ser_addr.sin_port = htons(6000); //服务器端口//发送消息sendto(sock, "hello world", strlen("hello world"), 0, (struct sockaddr*)&ser_addr, sizeof ser_addr);close(sock); //关闭套接字}}int main() {pra();return 0;
}
七.recvfrom接受UDP的消息
代码实例:
#include <cstdio>
#include<iostream>
#include<string.h> //memset
#include<arpa/inet.h> //htos
#include<sys/socket.h> //socket
#include<netinet/in.h> //struct sockaddr
#include<unistd.h> //closevoid pra() {int sock = socket(AF_INET, SOCK_STREAM, 0);if (sock != -1) {struct sockaddr_in my_addr;memset(&my_addr , 0, sizeof my_addr);my_addr.sin_family = AF_INET;my_addr.sin_port = htons(9000);my_addr.sin_addr.s_addr = INADDR_ANY; //绑定本地所有ipbind(sock, (struct sockaddr*)&my_addr, sizeof my_addr);//绑定本地IP和端口//接收信息while (1) {//定义一个IPv4地址结构存放发送者的信息struct sockaddr_in from_addr;socklen_t from_len = sizeof from_addr;unsigned char buf[1500] = "";int len = recvfrom(sock, buf, sizeof buf, 0, (struct sockaddr*)&from_addr, &from_len);char ip[16] = "";inet_ntop(AF_INET, &from_addr.sin_addr.s_addr, ip, sizeof 16);printf("消息来自 %s %hu ---->", ip, ntohs(from_addr.sin_port));printf("lem:%d msg:%s\n", len, buf);}close(sock); //关闭套接字} }int main() {pra();return 0;
}