new代码

发布时间 2023-11-09 09:43:41作者: 翎上
#include <WinSock2.h>
#include<ws2tcpip.h>
#include <stdio.h>
#include<windows.h>
#pragma comment(lib, "Ws2_32.lib")

struct hostent* FAR gethostbyname(
	const char *name
) ;

int WSAStartup(
   WORD      wVersionRequested,
   LPWSADATA lpWSAData
);

int WSACleanup(void);

int main(int argc, char **argv)
{
	//	调用 WSAStartup()函数,进行初始化操作 
	
	WSADATA wsaData;
	int iResult;
	DWORD dwError;
	int i = 0;
	struct hostent *remoteHost;
    char *host_name;
    struct in_addr addr;
    char **pAlias;
    if(argc != 2){
    	printf("usage: GetHostIP hostname\n");
    	return 1;
    }
    
	iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (iResult != 0)
	{
		printf("WSAStartup failed: %d\n", iResult);
		return 1;
	}
	host_name = argv[1];
    printf("Calling gethostbyname with %s\n", host_name);
    remoteHost = gethostbyname(host_name);
    if(remoteHost == NULL){
        dwError = WSAGetLastError();
        if(dwError != 0){
            if(dwError == WSAHOST_NOT_FOUND){
                printf("No data record found\n");
                return 1;
            }else {
                printf("Function failed with error:%d\n", dwError);
                return 1;
            }
        }
    }
    else{
        printf("Function returned:\n");
        printf("\tOfficial name: %s\n", remoteHost->h_name);
        for(pAlias = remoteHost->h_aliases; *pAlias != 0;pAlias++){
            printf("\tAddress type: ");
            switch (remoteHost->h_addrtype){
                case AF_INET:
                    printf("AF_INET\n");
                    break;
                    case AF_NETBIOS:
                        printf("AF_NETBIOS\n");
                        break;
                        default:
                            printf("%d\n",remoteHost->h_addrtype);
                            break;
            }
            printf("\tAddress length:%d\n", remoteHost->h_length);
            i=0;
            if(remoteHost->h_addrtype == AF_INET){
                while(remoteHost->h_addr_list[i] != 0){
                    addr.s_addr = *(u_long *)remoteHost->h_addr_list[i++];
                    printf("\tIP Address #%d: %s\n",i, inet_ntoa(addr));
                }
            }
            else if(remoteHost->h_addrtype == AF_NETBIOS){
                printf("NETBIOS address was returned\n");
            }
        }
        return 0;
    }

	//	调用 WSACleanup()函数,注销程序,释放资源 
	iResult = WSACleanup();
	if (iResult != 0)
	{
		printf("WSACleanup failed: %d\n", iResult);
		return -1;
	}
	return 0;
}