2010-02-06 47 views
2

即時通訊只是開始瞭解套接字,我已經給了這個代碼,我必須使端口查找邏輯工作。但問題是我不斷收到這個運行時錯誤,我不知道爲什麼?爲什麼在strcpy_s之後得到Debug斷言失敗?

// portlookup.cpp 
// Given a service name, this program displays the corresponding port number. 

#include <iostream> 
#pragma comment(lib, "ws2_32.lib") 
#include <winsock2.h> 
using namespace std; 

int main (int argc, char **argv) 
{ 
    char service[80]; // This string contains name of desired service 
    struct servent *pse; // pointer to service information entry 
    short port;   // Port # (in Network Byte Order) of desired service 

    if (argc < 2) 
    { 
     cout << "Please specify a service." << endl; 

    } 

    strcpy_s(service, sizeof(service), argv[1]); 

    WORD wVersion = 0x0202; 
    WSADATA wsaData; 
    int iResult = WSAStartup(wVersion, &wsaData); // Returns zero if successful 
    if (iResult != 0) { 
     cout << "Insufficient resources to startup WINSOCK." << endl; 
     return 0; 
    } 

    port = htons((u_short) atoi(service)); // 1st try to convert string to integer 
    if (port == 0) {      // if that doesn't work, call service function 
     pse = getservbyname(service,NULL); 
     if (pse) { 
      port = pse->s_port; 
     } 
     else 
     { 
      cout << "Invalid service request." << endl; 
      return INVALID_SOCKET; 
     } 
    } 

    cout << "Service: " << service << endl; 
    cout << "Port: " << htons(port) << endl; 

} 
+0

什麼運行時錯誤? – GManNickG 2010-02-06 21:09:00

+0

第一次使用strcpy之後,它表示Debug斷言失敗 – Zerobu 2010-02-06 21:11:14

+0

應該是strncpy嗎? – Anonymous 2010-02-06 21:13:54

回答

2

你的問題似乎是,你是不是通過命令行,你檢查的argc < 2,但是當它是< 2反正你執行strcpy_s。

在Visual Studio中,到了項目屬性對話框中,從那裏到調試 頁面,添加的服務名稱命令參數

並修正你的論點檢查代碼

if (argc < 2) 
{ 
    //cout << "Please specify a service." << endl; 
    cerr << "error: no service specified." << endl; 
    return EXIT_FAILURE; // return some non-zero value to indicate failure. 
} 
+1

他們還在學校裏教命令行嗎? – 2010-02-06 21:30:10

+0

@Richard:回想我的日子vi是_advanced_編輯器,調試是printf; D – 2010-02-06 21:41:11

+0

@John:你的意思是vi *不是高級編輯器?emacs什麼時候贏? – 2010-02-06 21:42:50

2

您需要使用參數啓動程序。 strcpy_s(service, sizeof(service),argv[1]);行假定你已經給出了程序1的參數,它將被存儲在argv [1]中。

如果您沒有使用任何參數運行它,argv [1]將爲NULL,您的程序將崩潰。

1

如果未指定參數,請務必退出。

if (argc < 2) 
{ 
    cout << "Please specify a service." << endl; 
    return 0; // exit! 
} 
0

也,

port = htons((u_short) atoi(service)); 
... 
cout << htons(port);