#include <stdio.h>
#include <strings.h>
#include "arpa/inet.h"
typedef union std {
unsigned short a;
unsigned char b[2];
} STD;
void udp_server() {
int sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (sock_fd < 0) {
perror("");
}
//绑定
//
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(9090);
//绑定自己本机的ip
// inet_pton(AF_INET,"192.168.127.129",&addr.sin_addr.s_addr);
addr.sin_addr.s_addr = INADDR_ANY; //通配地址
int ret=bind(sock_fd,(struct sockaddr*)&addr,sizeof(addr));
if(ret<0){
perror("");
}
struct sockaddr_in cli_addr;
socklen_t len = sizeof(cli_addr);
while (1){
char buf[128]="";
int n = recvfrom(sock_fd,buf, sizeof(buf),0,(struct sockaddr*)&cli_addr, &len);
printf("%s\n",buf);
sendto(sock_fd,buf,n,0,(struct sockaddr*)&cli_addr, sizeof(cli_addr));
}
close(sock_fd)
}
void udp_client() {
//ipv4的套接字结构体
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(9000);//转大端,这是目标机器的port
inet_pton(AF_INET, "192.168.127.1", &server_addr.sin_addr.s_addr);
// 创建套接字
int sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (sock_fd < 0) {
perror("");
}
while (1) {
char buf[128] = "";
fgets(buf, sizeof(buf), stdin);
buf[strlen(buf) - 1] = 0;
sendto(sock_fd, buf, strlen(buf), 0, (struct sockaddr *) &server_addr, sizeof(server_addr));
char read_buf[128] = "";
recvfrom(sock_fd, read_buf, sizeof(read_buf), 0, NULL, NULL);
printf("%s\n", read_buf);
}
}
void func2() {
//字符串ip地址转为整型数据
char buf_ip[] = "192.168.1.2";
int num = 0;
inet_pton(AF_INET, buf_ip, &num);
unsigned char *p = (char *) # //不定义为无符号容易出现负数。
printf("%d %d %d %d\n", *p, *(p + 1), *(p + 2), *(p + 3));
//将网络32位大端数据转为点分十进制
char ip[INET_ADDRSTRLEN] = ""; //INET_ADDRSTRLEN=16 255.255.255.2555\0,最大就是16位就够了。其中'\0'占一位
inet_ntop(AF_INET, &num, ip, INET_ADDRSTRLEN);
printf("ip=%s\n", ip);
}
void func1() {
int num = 0x01020304;//小端
short a = 0x0102;
int num2 = htonl(num);//小端转为大端数据。4030201
short a2 = htons(a);
printf("%x\n", a2);
printf("%x\n", num2);
printf("%x\n", ntohl(num2)); //大端再转为小端。
printf("%x\n", ntohs(a2)); //大端再转为小端。
}
int main() {
STD tmp;
tmp.a = 0x0102;
if (tmp.b[0] == 0x01) {
printf("大端");
} else {
printf("小端");
}
printf("Hello, World!\n");
func1();
func2();
return 0;
}
标签:udp,addr,实现,sock,C语言,include,sin,INET
From: https://www.cnblogs.com/c-x-a/p/17001513.html