红联首页 凝聚Linux人的力量
菜鸟过关 | 精华文档 | 同城人(交友) | 我与Linux的故事 | Linux新闻 | Linux视频 | Linux人才 | 软件下载 | 大学校园 | English
发新话题
打印

Linux Socket Programming

Linux Socket Programming

1. getname.c, get the host information, mainly the IP address if you know the host name.

[code]

/* As usual, make the appropriate includes and declare the variables. */

#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
    char *host, **names, **addrs;
    struct hostent *hostinfo;

/* Set the host in question to the argument supplied with the getname call,
    or default to the user's machine. */

    if(argc == 1) {
        char myname[256];
        gethostname(myname, 255);
        host = myname;
    }
    else
        host = argv[1];

/* Make the call to gethostbyname and report an error if no information is found. */

    hostinfo = gethostbyname(host);
    if(!hostinfo) {
        fprintf(stderr, "cannot get info for host: %s\n", host);
        exit(1);
    }

/* Display the hostname and any aliases it may have. */

    printf("results for host %s:\n", host);
    printf("Name: %s\n", hostinfo -> h_name);
    printf("Aliases:");
    names = hostinfo -> h_aliases;
    while(*names) {
        printf(" %s", *names);
        names++;
    }
    printf("\n");

/* Warn and exit if the host in question isn't an IP host. */

    if(hostinfo -> h_addrtype != AF_INET) {
        fprintf(stderr, "not an IP host!\n");
        exit(1);
    }

/* Otherwise, display the IP address(es). */

    addrs = hostinfo -> h_addr_list;
    while(*addrs) {
        printf(" %s", inet_ntoa(*(struct in_addr *)*addrs));
        addrs++;
    }
    printf("\n");
    exit(0);
}

[code end]

Note: this example code is extracted from book, Beginning Linux Programming, the 3rd edition.

2. getaddress.c, get the host name supposing you know its IP address.

#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
struct hostent *hostinfo;
struct in_addr *addr,address;

if(argc==1)
{
address.s_addr= inet_addr("127.0.0.1");
addr=&address;
}
else
{
address.s_addr= inet_addr(argv[1]);
addr=&address;
}
hostinfo = gethostbyaddr((char *)addr,sizeof(addr),AF_INET);
if(!hostinfo)
{
   fprintf(stderr, "Invalid IP address!\n");
   exit(1);
}
else
printf("Name: %s\n", hostinfo ->h_name);

exit(0);
}

Note: This example code is written by myself, and have been tested on Redhat Linux system. While I can not guarantee it works on other Linux operating system.

TOP

发新话题