欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

linux网络编程一

时间:2023-08-29
大小端

小端字节序:高位字节存储在内存的高地址处,也称为 主机字节序 PC机大多采用此模式
大端字节序:高位字节存储在内存的低地址处,也称为 网络字节序;网络端传输

大小端的不一致需要转换

字节序 IP地址与端口port转换

#include uint32_t htonl(uint32_t hostlong);//IP 主机->网络uint16_t htons(uint16_t hostshort);//port 主机->网络uint32_t ntohl(uint32_t netlong);//IP 网络->主机uint16_t ntohs(uint16_t netshort);//port 网络->主机

IP地址转换

需要做的一些列转换192.168.0.1->string->atoi->int->htinl->网络
直接使用函数 inet_pton,inet_ntop

#include

convert IPv4 and IPv6 addresses from text to binary form

int inet_pton(int af, const char *src, void *dst);//本机->网络字节序

convert IPv4 and IPv6 addresses from binary to text form

const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);//网络字节序->本机

网络字节序的转换

#include#include#include#includeunion{ short value; char union_bytes[sizeof(short)];}test;//确认大端还是小端void byteorder(){ test.value=0x1122; if(test.union_bytes[0]==0x11 && test.union_bytes[1]==0x22) { printf("big endiann"); } else if(test.union_bytes[0]==0x22 && test.union_bytes[1]==0x11) { printf("little endiann"); } else { printf("unknown"); }}//宏定义函数,实现大小端转化怒#define BLSwap16(a) ((((a&0xff00)>>8) | (a&0x00ff)<<8))#define BLSwap32(a) (((a&0xff000000)>>24) | ((a&0x00ff0000)>>8) | ((a&0x0000ff00)<<8)|((a&0x000000ff)<<24))void main(){ byteorder(); short a = 0x1234; short b = htons(a); printf("short b=%xn",b); b = BLSwap16(a); printf("BLSwap short b=%xn",b); int c = 0x12345678; int d = htonl(c); printf("long int d=%xn",d); d = BLSwap32(c); printf("BLSwap32 long int d=%xn",d);}

输出结果

(base) wy@ubuntu:~/network$ ./a.out little endianshort b=3412BLSwap short b=3412long int d=78563412BLSwap32 long int d=78563412

IP地址转换

#include #include #include #include int main(int argc, char *argv[]) { unsigned char buf[sizeof(struct in6_addr)]; int domain, s; char str[INET6_ADDRSTRLEN]; if (argc != 3) { fprintf(stderr, "Usage: %s {i4|i6|} stringn", argv[0]); exit(EXIT_FAILURE); } domain = (strcmp(argv[1], "i4") == 0) ? AF_INET : (strcmp(argv[1], "i6") == 0) ? AF_INET6 : atoi(argv[1]); s = inet_pton(domain, argv[2], buf); if (s <= 0) { if (s == 0) fprintf(stderr, "Not in presentation format"); else perror("inet_pton"); exit(EXIT_FAILURE); } if (inet_ntop(domain, buf, str, INET6_ADDRSTRLEN) == NULL) { perror("inet_ntop"); exit(EXIT_FAILURE); } printf("%sn", str); exit(EXIT_SUCCESS); }

(base) wy@ubuntu:~/network$ ./a.out i6 1:0:0:0:0:0:0:81::8(base) wy@ubuntu:~/network$ ./a.out i6 0:0:0:0:0:FFFF:204.152.189.116::ffff:204.152.189.116(base) wy@ubuntu:~/network$ ./a.out i6 0:0:0:0:0:0:0:0::

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。