I have interesting problem with IP address detection in C++. I used inet_pton function and sockaddr_in structure. If string is valid IPv4 or IPv6, function will return AF_INET or AF_INET6. Otherwise zero is returned.
Code below does not work. SIGSEGV in condition with IPv6 detection when input is valid IPv6 address (IPv4 address and invalid address are OK). Same problem is after removal of IPv4 condition.
#include <string>
#include <iostream>
#include <arpa/inet.h>
using namespace std;
int isIP(string);
int main(int argc, char *argv[]){
string s = "::1";
int test = isIP(s);
return 0;
}
int isIP(string addr){
struct sockaddr_in sa;
if((inet_pton(AF_INET, addr.c_str(), &(sa.sin_addr))))
return AF_INET;
if((inet_pton(AF_INET6, addr.c_str(), &(sa.sin_addr))))
return AF_INET6;
return 0;
}
But when is function IsIP changed like codes below, everything is OK.
int isIP(string addr){
struct sockaddr_in sa;
cout << addr + "\n";
if(inet_pton(AF_INET, addr.c_str(), &(sa.sin_addr)))
return AF_INET;
if(inet_pton(AF_INET6, addr.c_str(), &(sa.sin_addr)))
return AF_INET6;
return 0;
}
or
int isIP(string addr){
struct sockaddr_in sa, sa2;
if((inet_pton(AF_INET, addr.c_str(), &(sa.sin_addr))))
return AF_INET;
if((inet_pton(AF_INET6, addr.c_str(), &(sa2.sin_addr))))
return AF_INET6;
return 0;
}
or
int isIP(string addr){
struct sockaddr_in sa;
int r1 = inet_pton(AF_INET, addr.c_str(), &(sa.sin_addr));
int r2 = inet_pton(AF_INET6, addr.c_str(), &(sa.sin_addr));
if(r1)
return AF_INET;
if(r2)
return AF_INET6;
return 0;
}
What is that problem in first implementation of isIP function?