I am build my own function to aquire the local ip address and together using another function provided from this site Get the IP Address of local computer
I am using a 16-length character array, and this is the return value of during progress, 192.168.056.001Íýýýý ,it should be like"192.168.056.001" and a '\0' ,something must be wrong here, just can't figure out.And this cause problems when I sending it through the ethernet by creating UDP packets.
char* YourApplication::GetMyIP() {
char* IPAdd = new char[16];
if (YourApplication::GenerateIP(MyIP)) {
int b1 = MyIP.b1;
int hundreds,tens;
if (b1 < 100) {
IPAdd[0] = '0';
if (b1 < 10) {
IPAdd[1] = '0';
IPAdd[2] = b1 + 48;
}
else {
tens = b1 / 10;
IPAdd[1] = tens + 48;
IPAdd[2] = b1 % 10 + 48;
}
}
else {
hundreds = b1 / 100;
IPAdd[0] = hundreds+48;
tens = (b1 - 100*hundreds) / 10;
IPAdd[1] = tens+48;
IPAdd[2] = (b1 - 100 * hundreds - 10 * tens) + 48;
}
IPAdd[3] = '.';
int b2 = MyIP.b2;
if (b2 < 100) {
IPAdd[4] = '0';
if (b2 < 10) {
IPAdd[5] = '0';
IPAdd[6] = b2 + 48;
}
else {
tens = b2 / 10;
IPAdd[5] = tens + 48;
IPAdd[6] = b2 % 10 + 48;
}
}
else {
hundreds = b2 / 100;
IPAdd[4] = hundreds + 48;
tens = (b2 - 100 * hundreds) / 10;
IPAdd[5] = tens + 48;
IPAdd[6] = (b2 - 100 * hundreds - 10 * tens) + 48;
}
IPAdd[7] = '.';
int b3 = MyIP.b3;
if (b3 < 100) {
IPAdd[8] = '0';
if (b3 < 10) {
IPAdd[9] = '0';
IPAdd[10] = b3 + 48;
}
else {
tens = b3 / 10;
IPAdd[9] = tens + 48;
IPAdd[10] = b3 % 10 + 48;
}
}
else {
hundreds = b3 / 100;
IPAdd[8] = hundreds + 48;
tens = (b3 - 100 * hundreds) / 10;
IPAdd[9] = tens + 48;
IPAdd[10] = (b3 - 100 * hundreds - 10 * tens) + 48;
}
IPAdd[11] = '.';
int b4 = MyIP.b4;
if (b4 < 100) {
IPAdd[12] = '0';
if (b4 < 10) {
IPAdd[13] = '0';
IPAdd[14] = b4 + 48;
}
else {
tens = b4 / 10;
IPAdd[13] = tens + 48;
IPAdd[14] = b4 % 10 + 48;
}
}
else {
hundreds = b4 / 100;
IPAdd[12] = hundreds + 48;
tens = (b4 - 100 * hundreds) / 10;
IPAdd[13] = tens + 48;
IPAdd[14] = (b4 - 100 * hundreds - 10 * tens) + 48;
}
}
return IPAdd;
}
And below is that function from that site:
bool YourApplication::GenerateIP(IPv4 & myIP)
{
char szBuffer[1024];
#ifdef WIN32
WSADATA wsaData;
WORD wVersionRequested = MAKEWORD(2, 0);
if (::WSAStartup(wVersionRequested, &wsaData) != 0)
return false;
#endif
if (gethostname(szBuffer, sizeof(szBuffer)) == SOCKET_ERROR)
{
#ifdef WIN32
WSACleanup();
#endif
return false;
}
struct hostent *host = gethostbyname(szBuffer);
if (host == NULL)
{
#ifdef WIN32
WSACleanup();
#endif
return false;
}
//Obtain the computer's IP
myIP.b1 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b1;
myIP.b2 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b2;
myIP.b3 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b3;
myIP.b4 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b4;
#ifdef WIN32
WSACleanup();
#endif
return true;
}