Skip to content

Instantly share code, notes, and snippets.

@jorben
Last active December 3, 2015 01:38
Show Gist options
  • Save jorben/da7acb8511e060e7b265 to your computer and use it in GitHub Desktop.
Save jorben/da7acb8511e060e7b265 to your computer and use it in GitHub Desktop.
巧妙的获取本机ip地址
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
char* get_local_addr(char* buf, size_t len);
int main(int argc, char** argv)
{
char strLocalAddr[16] = "0.0.0.0\0";
get_local_addr(strLocalAddr, sizeof(strLocalAddr));
printf("local address: %s\n", strLocalAddr);
return 0;
}
char* get_local_addr(char* buf, size_t len)
{
if(16 > len)
return buf;
memset(buf, '\0', len);
int32_t iClientSockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(iClientSockfd < 0 )
{
return buf;
}
struct sockaddr_in stINETAddr;
stINETAddr.sin_addr.s_addr = inet_addr("192.168.0.1");
stINETAddr.sin_family = AF_INET;
stINETAddr.sin_port = htons(18888);
int32_t iCurrentFlag = fcntl(iClientSockfd, F_GETFL, 0);
fcntl(iClientSockfd, F_SETFL, iCurrentFlag | O_NONBLOCK);
if( 0 != connect(iClientSockfd, (struct sockaddr *) &stINETAddr, sizeof(stINETAddr)) )
{
close(iClientSockfd);
return buf;
}
struct sockaddr_in stINETAddrLocal;
socklen_t iAddrLenLocal = sizeof(stINETAddrLocal);
getsockname(iClientSockfd, (struct sockaddr *)&stINETAddrLocal, &iAddrLenLocal);
close(iClientSockfd);
snprintf(buf, len, "%s", inet_ntoa(stINETAddrLocal.sin_addr));
return buf;
}
@jorben
Copy link
Author

jorben commented Dec 2, 2015

第33行:
对于双网卡(通常是一块内网一块外网)设备,设置socket服务端ip为外网地址时(比如8.8.8.8)则将获得本机外网网卡ip,设置socket服务端ip为内网地址时(比如192.168.0.1)则将获得本机内网网卡ip。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment