Linux网络编程IPv4和IPv6的inet_addr、inet_aton、inet_pton等函数小结

 

知识背景:

210.25.132.181属于IP地址的ASCII表示法,也就是字符串形式。英语叫做IPv4 numbers-and-dots notation。

如果把210.25.132.181转换为整数形式,是3524887733,这个就是整数形式的IP地址。英语叫做binary data。(其实binary是二进制的意思)

详细介绍,请参考: 网络字节序与主机字节序的转换 

 

 

问题所在:

如何在字符串形式的IP和整数形式的IP之间转换呢?

 

 

转换函数:

int inet_aton(const char *cp, struct in_addr *inp);

in_addr_t inet_addr(const char *cp);

in_addr_t inet_network(const char *cp);

int inet_pton(int af, const char *src, void *dst);

const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt);

 

参考:http://beej.us/guide/bgnet/output/html/multipage/inet_ntopman.html

=============================================================

IPv4:

 

IP字符串 ——》 网络字节流

inet_addr、inet_network、inet_aton

 

程序代码:

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/types.h> int main() { char ip[] = "192.168.0.74"; long r1, r2, r3; //long struct in_addr addr; r1 = inet_addr(ip); //返回网络字节序 if(-1 == r1){ printf("inet_addr return -1/n"); }else{ printf("inet_addr ip: %ld/n", r1); } r2 = inet_network(ip); //返回主机字节序 if(-1 == r2){ printf("inet_addr return -1/n"); }else{ printf("inet_network ip: %ld/n", r2); printf("inet_network ip: %ld/n", ntohl(r2)); //ntohl: 主机字节序 ——> 网络字节序 } r3 = inet_aton(ip, &addr); //返回网络字节序 if(0 == r3){ printf("inet_aton return -1/n"); }else{ printf("inet_aton ip: %ld/n", addr.s_addr); } /***** 批量注释的一种方法 *****/ #if 0 r3 = inet_aton(ip, addr); if(0 == r3){ printf("inet_aton return -1/n"); }else{ printf("inet_aton ip: %ld/n", ntohl(addr.s_addr)); } #endif return 0; }

运行结果:

[work@db-testing-com06-vm3.db01.baidu.com net]$ gcc -W -o inet_addr inet_addr.c
[work@db-testing-com06-vm3.db01.baidu.com net]$ ./inet_addr                    
inet_addr ip: 1241557184
inet_network ip: -1062731702
inet_network ip: 1241557184
inet_aton ip: 1241557184 

 

--------------------------------------------------------------------------

 

IP字符串 《——》 网络字节流

inet_addr、inet_aton、inet_ntoa

 

 程序代码:

#include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> int main(int argc, char *argv[]) { char ip1[] = "192.168.0.74"; char ip2[] = "211.100.21.179"; struct in_addr addr1, addr2; long l1, l2; l1 = inet_addr(ip1); //IP字符串——》网络字节 l2 = inet_addr(ip2); printf("IP1: %s/nIP2: %s/n", ip1, ip2); printf("Addr1: %ld/nAddr2: %ld/n", l1, l2); memcpy(&addr1, &l1, 4); //复制4个字节大小 memcpy(&addr2, &l2, 4); printf("%s <--> %s/n", inet_ntoa(addr1), inet_ntoa(addr2)); //注意:printf函数自右向左求值、覆盖 printf("%s/n", inet_ntoa(addr1)); //网络字节 ——》IP字符串 printf("%s/n", inet_ntoa(addr2)); return 0; }

运行结果:

 

[work@db-testing-com06-vm3.db01.baidu.com net]$ gcc -W -o inet_ntoa inet_ntoa.c 

[work@db-testing-com06-vm3.db01.baidu.com net]$ ./inet_ntoa                                      

IP1: 192.168.0.74

IP2: 211.100.21.179

Addr1: 1241557184

Addr2: 3004523731

192.168.0.74 <--> 192.168.0.74

192.168.0.74

211.100.21.179

 

============================================================= 

 

IPv6:

 

IPv4 字符串 《——》网络字节流

inet_pton、inet_ntop

 

程序代码:

 

#include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> int main() { char ip[] = "192.168.0.74"; struct in_addr addr; int ret = inet_pton(AF_INET, ip, (void *)&addr); //IP字符串 ——》网络字节流 if(0 == ret){ printf("inet_pton error, return 0/n"); return -1; }else{ printf("inet_pton ip: %ld/n", addr.s_addr); printf("inet_pton ip: 0x%x/n", addr.s_addr); } const char *pstr = inet_ntop(AF_INET, (void *)&addr, ip, 128); //网络字节流 ——》IP字符串 if(NULL == pstr){ printf("inet_ntop error, return NULL/n"); return -1; }else{ printf("inet_ntop ip: %s/n", ip); } return 0; }

运行结果:

[work@db-testing-com06-vm3.db01.baidu.com net]$ gcc -W -o inet_ptoa inet_ptoa.c
[work@db-testing-com06-vm3.db01.baidu.com net]$ ./inet_ptoa                    
inet_pton ip: 1241557184
inet_pton ip: 0x4a00a8c0
inet_ntop ip: 192.168.0.74

 

 

--------------------------------------------------------------------------

IPv6 字符串 《——》网络字节流

inet_pton、inet_ntop

 

程序代码:

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> 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|<num>} string/n", argv[0]); exit(EXIT_FAILURE); } domain = (strcmp(argv[1], "i4") == 0) ? AF_INET:(strcmp(argv[1], "i6") == 0) ? AF_INET6 : atoi(argv[1]); //IP字符串 ——》网络字节流 s = inet_pton(domain, argv[2], buf); if(s<=0){ if(0 == s) fprintf(stderr, "Not in presentation format/n"); else perror("inet_pton"); exit(EXIT_FAILURE); } //网络字节流 ——》IP字符串 if(inet_ntop(domain, buf, str, INET6_ADDRSTRLEN) == NULL){ perror("inet ntop/n"); exit(EXIT_FAILURE); } printf("%s/n", str); exit(EXIT_SUCCESS); } 运行结果:

[work@db-testing-com06-vm3.db01.baidu.com net]$ gcc -W -o inet_ptoa6 inet_ptoa6.c                              
[work@db-testing-com06-vm3.db01.baidu.com net]$ ./inet_ptoa6 i6 0:0:0:0:0:FFFF:204.152.189.116  
::ffff:204.152.189.116
[work@db-testing-com06-vm3.db01.baidu.com net]$ ./inet_ptoa6 i4 204.152.189.116              
204.152.189.116

 

参考:http://www.kernel.org/doc/man-pages/online/pages/man3/inet_pton.3.html

 

 

 

 

转载于:https://www.cnblogs.com/springmvc-hibernate/archive/2010/12/27/2484178.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/462816.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

MySQL中alter table range partition

最近在用MySQL开发新功能时&#xff0c;使用到了alter table range partition的功能&#xff0c;在此总结下mysql innodb支持的alter table range partition相关功能。mysql的版本是8.0.22, os: linux ubuntu 对alter range partition的操作主要由以下几个&#xff1a; analy…

可恶,谁占用了我的80端口?

下午在室友的本本上上网&#xff0c;突然想看一个新闻系统&#xff0c;他的本上没有安装环境&#xff0c;于是下载一个wamp,安装。运行wamp&#xff0c;晕...怎么只有1个服务在运行&#xff0c;导致我的localhost打不开&#xff0c;看了一下mysql服务运行正常&#xff0c;apach…

laravel命令

新建控制器 php artisan make:controller IssuesController 新建控制器并自动生成对应RESTful风格路由相关CURD方法 php artisan make:controller IssuesController -r 新建一个迁移文件 php artisan make:migration create_issues_table --createissues 回滚上一次迁移的内容 …

CMakeList.txt中设置一个可变的变量的值(bool)

在CMakeList.txt中有个bool变量&#xff0c;在debug模式下需要设置为OFF&#xff0c;在其他模式(release、thread、leak)下设置为ON&#xff0c;需要在makefile中将该值设置不同的值&#xff0c;CMakeList.txt中增加的代码如下&#xff1a; IF(CMAKE_BUILD_TYPE STREQUAL &quo…

iOS开发那些事--创建基于故事板的iOS 6的HelloWorld

基于故事板的HelloWorld工程 Storyboard&#xff08;故事板&#xff09;是用来替代xib的技术&#xff0c;也是iOS 5最重要的新特性之一。我们用Storyboard&#xff08;故事板&#xff09;重构HelloWorld。 使用故事板重构HelloWorld 勾选“Use Storyboards”项。 工程创建完成之…

Android——Ubuntu android NDK 配置

前提工作&#xff1a; 在虚拟机ubuntu下载linux版本&#xff0c;终端cd到解压根目录 第一步:make -v 和 gcc -v 检测 第二步: 检测没有错误,输入命令: ./build/host-setup.sh 会出现错误&#xff0c;必须的。要进行修改&#xff1a;编辑 build/host-setup.sh 修改#!/bin/sh 为#…

.Net 2.0中使用扩展方法

大家都知道扩展方法是不能直接在2.0中使用的需要引用一个‍System.Core的dll不过现在有更加简单的方法了只要在工程项目中加入以下代码就OK啦‍namespace System.Runtime.CompilerServices{[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTarge…

mysql中的if [not] exists

最近在MySQL数据库的基础上开发分布式的数据库&#xff0c;需要支持一个if [not] exists语法。学习了SQL语法解析部分&#xff0c;总结下&#xff1a; 1、在MySQL中&#xff0c;创建表时支持create table if not exists db.table_name .... create table if not exists test1…

oracle Merge 函数

Merge用来从一个表中选择一些数据更新或者插入到另一个表中。而最终是用更新还是用插入的方式取决于该语句中的条件。下面我们简单的举一个例子&#xff1a;SQL> create table merge_test1(a number,b varchar2(20)) 表已创建。SQL> create table merge_test2(a number,b…

Linux下将两个10G的文件打包成一个文件需要多久

Linux下将两个10G的文件打包成一个文件需要多久 | 公云网博客Linux下将两个10G的文件打包成一个文件需要多久发表于 2012 年 9 月 19 日 由 refactor微博上kevin_prajna提了一个问题&#xff1a;“求Linux下一打包工具&#xff0c;需求&#xff1a;能把两个10G的文件打包成一个…

基于美国人口数据分析

https://github.com/jakevdp/PythonDataScienceHandbook 英文看不懂的话请自行选择中文翻译版转载于:https://www.cnblogs.com/Lucifer77/p/10741538.html

MySQL innodb每行数据长度的限制

今天在使用MySQL innodb时&#xff0c;create table时&#xff0c;报出这样的一个错误: Row size too large. The maximum row size for the used table type, not counting BLOBs, is 8126. You have to change some columns to TEXT or BLOBs 查阅MySQL的官方资料才发现&…

Lucene4:创建查询,并高亮查询关键词

1. 要求 环境&#xff1a; Lucene 4.1版本/IKAnalyzer 2012 FF版本/mmseg4j 1.9版本功能&#xff1a;  1).高亮查询演示 注意&#xff1a; 此篇文章开始&#xff0c;索引目录将不再使用示范目录&#xff0c;而是使用真实的数据。即LUCENE_INDEX_DIR "C:\\lucene\\data&…

字典的相关函数

#coding:utf-8""" #第一种写法 """ def func(a,b,c,*,d):print(a,b,c)print(d)func(1,2,3,d4)""" #第二种写法 """ def func(*args,b,c,**kwargs):print(args)print(kwargs)print(b,c)# 函数调用处 func(1,2,3,4,…

python实例31[文件夹清理]

使用&#xff1a; foldercleanup.py -d 10 -k c:\test\keepfile.txt c:\test 表示对c:\test目录只保留最近10天的子文件夹和keepfile.txt中指定的子文件夹。 代码&#xff1a; importosimportos.pathimportdatetime defgetOption(): fromoptparse importOptionParser de…

MySQL中的alter table操作之add/modify/drop列

alter table的操作有增加列、删除列和修改列的长度等 create table t1 (c1 int primary key) engine innodb; // 增加一个列c2 alter table t1 add c2 varchar(16379); drop table t1;create table t1 (c1 int primary key, c2 varchar(50)) engine innodb; // 将列c2长度更…

SUSE Linux启动过程执行脚本顺序

网上看到的&#xff0c;备忘 mbr->grub->menu.lst->vmlinuz(linux)->initrd->etc/inittab->/etc/rc.status->/etc/sysconfig/boot->/etc/init.d/boot.d/*->/etc/init.d/boot.local->/etc/rc.d/rc*.d/*->mingetty->login->/etc/profile.…

jdk8 Function

例子 1&#xff1a; // 定义function Function<String, String> fun parm -> { // 这里是定function中的逻辑 return String.valueOf(parm "xing"); };Function<String, String> fun1 parm -> { // 这里是定function中的逻辑 return String.val…

std::unique_ptr<T>与boost::scoped_ptr<T>的特殊性

std::unique_ptr<T>与boost::scoped_ptr<T>的底层实现原理类型&#xff0c;不清楚是谁"借鉴"另一个的实现的&#xff0c;但这不重要。 std::unique_ptr<T>与boost::scoped_ptr<T> 都禁用了拷贝构造和赋值函数&#xff0c;所以不能作为STL容…

winform Outlookbar

控件提供了一种类似Outlook方式的工具条&#xff0c;用来切换各种业务窗口&#xff0c;用上这个控件&#xff0c;肯定为您的程序增色不少。这个控件结合上面介绍的布局控件"WeifenLuo.WinFormsUI.Docking"&#xff08;具体见文章WinForm界面开发之布局控件"Weif…