Segmentation Fault


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>

struct hostent* hostPtr;

char* getHostIPAddress() 
    {
        struct in_addr *addr_ptr;
		// the first address in the list of host addresses
        addr_ptr = (struct in_addr *)hostPtr->h_addr_list;
		// changed the address format to the Internet address in standard dot notation
        return inet_ntoa(*addr_ptr);
    }    
    


So basically whats happening everything is going good until: return inet_ntoa(*addr_ptr); and then I get a segementation fault. This works with my Server source, but not with my Client source for some reason. Is there a better way to retrieve the ip then this method.
Have you checked to make sure addr_ptr isn't NULL?
Last edited on
So I checked to see if addr_ptr was NULL and it wasn't.
are you sure inet_ntoa is actually returning something?
Yeah, I agree with iHutch105. A null pointer being used will segfault. Other than that I don't know what else it would be. I goofed and did that earlier today actually with some code.
well if inet_ntoa isnt returning anything because of an error then its not going to return anything which i think would generate a segfault, because the variable recieving the char * would be garbage memory
Have you checked if hostPtr is NULL?
Your problems begin with the declaration of the function.
 
char* getHostIPAddress()

Why are your returning a pointer? A pointer to what?

And then, there's the problem of what to do if the function fails? You can throw an exception, in which case the function can return whatever you like, or it can return a bool.

If we assume it throws an exception, you could get away with:
 
std::string getHostIPAddress()


The rest could look like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <unistd.h>
#include <sys/param.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <stdexcept>

std::string getHostIPAddress()
{
	char name[MAXHOSTNAMELEN];
	gethostname(name, sizeof(name));

	if (struct hostent *hent = gethostbyname(name))
	{
		if (hent->h_addrtype == AF_INET && hent->h_length == sizeof(uint32_t))
		{
			struct in_addr sin_addr;
			sin_addr.s_addr = *reinterpret_cast<in_addr_t*>(hent->h_addr_list[0]);
			return inet_ntoa(sin_addr);
		}

		throw std::runtime_error("not an IPV4 address");
	}

	throw std::runtime_error("gethostbyname failed");
}
Topic archived. No new replies allowed.