第 3 章:套接字编程简介

IP echo 程序

inet_ptoninet_ntop 写的一个程序, 接收一个 ddd.ddd.ddd.ddd 格式的 IP 地址, 然后将它转换成 sockaddr_in 结构, 然后再从结构中转换出一个 IP 地址, 并打印出来。

如果一切正常的话, 打印的 IP 应该和输入的 IP 一样:

#include <stdio.h>  // printf
#include <stdlib.h> // exit, malloc
#include <arpa/inet.h>  // inet_ntop, inet_pton
#include <netinet/in.h> // struct sockaddr_in, AF_INET
#include <string.h> // strlen

int 
main(int argc, char *argv[])
{
    char *buf;
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(struct sockaddr_in));

    if (argc != 2) {
        fprintf(stderr, "usage: a.out <ddd.ddd.ddd.ddd>\n");
        exit(1);
    }

    // 将 ip 转换为地址

    if (inet_pton(AF_INET, argv[1], &addr.sin_addr) == -1) {
        perror("inet_pton error");
        exit(2);
    }

    // 将地址转换为 ip

    buf = malloc(strlen(argv[1]) + 1);

    if (inet_ntop(AF_INET, &addr.sin_addr, buf, INET_ADDRSTRLEN) == NULL) {
        perror("inet_ntop error");
        exit(3);
    }

    // 打印 ip

    printf("The input ip is: %s\n", buf);

    free(buf);

    return 0;
}

运行:

$ ./a.out 123.123.123.123
The ip you input is: 123.123.123.123

留言

comments powered by Disqus

Table Of Contents

Previous topic

第 2 章:传输层:TCP 、 UDP 和 SCTP

Next topic

第 4 章:基本 TCP 套接字编程