2016-09-27 107 views
2

我在這裏相當新,我試圖測試自己的套接字程序。創建套接字C++

如何創建套接字?這是我想要做的:

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 { 
    //... 
    } 
} 

編輯:這兩個鏈接幫助了很多瞭解套接字。請看看他們:

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

的問題是有點含糊,嘗試尋找在這裏:http://beej.us/guide/bgnet/ – Charlie

+0

@Charlie,謝謝! :D – Johnson

+0

你的代碼有什麼問題?什麼是錯誤(如果發生錯誤)?你期望的行爲是什麼,你會得到哪一個? – Garf365

回答

0

既然你說你是在Windows和我假設你顯示的代碼是完整的代碼它不工作的原因是因爲沒有呼叫WSAStartup已尚未作出,這個函數初始化網絡庫,並應任何網絡操作之前​​被調用(如創建一個套接字):

//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 { 
    //... 
    } 
}