为什么我在strcpy_s之后得到Debug断言失败?

时间:2010-02-06 21:05:26

标签: c++ sockets networking

我刚刚开始学习套接字,我已经获得了这段代码,我必须让端口查找逻辑工作。但问题是我一直得到这个运行时错误,我不知道为什么?

// 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;

}

4 个答案:

答案 0 :(得分:2)

您需要使用参数启动程序。行strcpy_s(service, sizeof(service),argv[1]);假设您已经给出了程序1参数,该参数将存储在argv [1]中。

如果你没有使用任何参数运行它,argv [1]将为NULL并且你的程序将崩溃。

答案 1 :(得分:2)

您的问题似乎是您没有通过命令行,请检查argc&lt; 2,但是当它是&lt; 2无论如何你都要执行strcpy_s。

在Visual Studio中,进入“项目属性”对话框,然后转到调试页面 并将服务名称添加到 Command Arguments

修复你的论据检查代码

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

答案 2 :(得分:1)

如果未指定参数,请务必退出。

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

答案 3 :(得分:0)

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