ZBLOG

inet_pton

inet_pton is a function in the C programming language that converts an IPv4 or IPv6 address from text format to binary format. The name inet_pton stands for “Internet presentation to network” and is part of the standard networking library on Unix-like operating systems.

The syntax of the inet_pton function is as follows:

#include <arpa/inet.h>

int inet_pton(int af, const char *src, void *dst);
  • af: An integer specifying the address family. This can be either AF_INET for IPv4 or AF_INET6 for IPv6.
  • src: A pointer to a string containing the IP address in text format.
  • dst: A pointer to a buffer where the converted binary IP address will be stored.

The return value of inet_pton is 1 if the conversion was successful, 0 if src does not contain a valid IP address, or -1 if an error occurred.

Here’s an example usage of the inet_pton function:

#include <stdio.h>
#include <arpa/inet.h>

int main() {
    const char* ip_address = "192.168.1.1";
    struct in_addr ipv4_addr;

    int result = inet_pton(AF_INET, ip_address, &ipv4_addr);

    if (result == 1) {
        printf("Binary representation: %u\n", ipv4_addr.s_addr);
    } else if (result == 0) {
        printf("Invalid IP address.\n");
    } else {
        perror("Error converting IP address.");
    }

    return 0;
}

In this example, we convert the IPv4 address “192.168.1.1” from text format to binary format using the inet_pton function with AF_INET as the address family parameter. The resulting binary representation is printed to stdout.

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://sdn.0voice.com/?id=992

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?