Johnson Johnson - 2 months ago 7
C++ Question

Creating a socket C++

I'm fairly new here and I'm trying to test my own sockets program.

How would one create a socket? Here is what I'm trying to do:

int main(int argc, char *argv[]) {
int socket_addr;
struct sockaddr_in server;
char message[100], server_message[100];

// Creates the socket
socket_addr = socket(AF_INET, SOCK_STREAM, 0);
if (socket_addr == -1) {
cout << "Could not create the socket!";
} else {
//...
}
}


EDIT: These two links helped out a lot on understanding sockets. Please look at them:

1) http://beej.us/guide/bgnet/
2) https://msdn.microsoft.com/en-us/library/windows/desktop/ms742213(v=vs.85).aspx

Answer

Since you said you're on windows and I'm assuming the code you showed is the full code the reason it's not working is because of no call to WSAStartup has been made yet, this function initializes the network library and should be called before any network operation (like creating a socket):

//your includes here..

#pragma comment(lib, "ws2_32.lib") // link with the network library

int main(int argc, char *argv[]) {
    int socket_addr;
    struct sockaddr_in server;
    char message[100], server_message[100];

    int wsaRes = 0;
    WSADATA wsaData = {0};
    wsaRes = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if(wsaRes != 0)
    {
      std::cerr << "WSAStartup failed!";
      return -1; 
    }
    // Creates the socket
    socket_addr = socket(AF_INET, SOCK_STREAM, 0);
    if (socket_addr == INVALID_SOCKET) {
        cout << "Could not create the socket!";
    } else {
    //...
    }
}