首页 > 代码库 > C++实现获取本机机器名及外网IP代码

C++实现获取本机机器名及外网IP代码

#include "stdafx.h"
#include <WINSOCK2.H>
#include <urlmon.h>
 
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "urlmon.lib")
 
#define MAX_SIZE 1024
 
 
int GetLocalIP();
int GetInternetIP();
 
int main(int argc, char* argv[])
{
    GetLocalIP();
    GetInternetIP();
    return 0;
}
 
 
int GetLocalIP()
{
    WSADATA wsaData;
    int err = WSAStartup(MAKEWORD(2, 0), &wsaData);
    if (err != 0)
    {
        return err;
    }
 
    char szHostName[MAX_PATH] = {0};
    int nRetCode;
    nRetCode = gethostname(szHostName, sizeof(szHostName));
 
    char* lpLocalIP;
    PHOSTENT hostinfo;
 
    if (nRetCode != 0)
    {
        return WSAGetLastError();        
    }
 
    hostinfo = gethostbyname(szHostName);
    lpLocalIP = inet_ntoa(*(struct in_addr*)*hostinfo->h_addr_list);
 
    if (szHostName != NULL)
    {
        printf("主机名: %s\n", szHostName);
        printf("本地IP: %s\n", lpLocalIP);
    }
 
    WSACleanup();
    return 0;
}
 
int GetInternetIP()
{
    char buf[MAX_PATH] = {0};    //把网页中读出的数据放在此处
    char chTempIp[128] = {0};
    char chIP[64] = {0};        //最终存放IP在此
 
    //将网页数据写入c:\i.ini文件中
    URLDownloadToFile(0, "http://iframe.ip138.com/ic.asp", "c:\\i.ini", 0, NULL);
 
    FILE *fp = fopen("c:\\i.ini", "r");
    if (fp != NULL)
    {
        //
        fseek(fp, 0, SEEK_SET);
        fread(buf, 1, MAX_PATH, fp);
        fclose(fp);
 
        //在buf中查找 [ 的位置, iIndex是buf中从[开始剩下的字符串,包括[这个字符串
        char* iIndex = strstr(buf, "[");
        if (iIndex)
        {
            sprintf(chTempIp, "%s", iIndex);
            int nBuflen = strlen(chTempIp);
 
            for (int i = 0; i < nBuflen; i++)
            {
                chIP[i] = chTempIp[i+1];
 
                //如果发现有 ] 则截断
                if (chTempIp[i] == ‘]‘)
                {
                    chIP[i-1] = ‘\0‘;
                    //printf("外网IP: %s\n", chIP);
                }
            }
        }
 
    }
 
    printf("外网IP: %s\n", chIP);
    remove("c:\\i.ini");
 
    return 0;
 
}
<style type="text/css"> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }</style>