Frage

I'm writing a simple client-server application which uses async type sockets. However, when I send a message from a client, I'm getting a buffer overrun exception. Client code:

#include "stdafx.h"
#include <conio.h> 
#include <winsock.h>
#include <process.h>
#include <stdlib.h>
#include <Windows.h>

#pragma comment(lib, "wsock32.lib")

#define CS_ERROR 1
#define CS_OK 0

char send_buf[1000];
char recv_buf[1000];

void MyFunction(void * Arg)
{   
    while(1)
    {         
        int Socket=(*(int *)Arg);
        send(Socket, send_buf,1000,0);  
        int n = recv(Socket,recv_buf,1000,0);
        recv_buf[n]=0;
        printf(" Answer from Server: %s",&recv_buf[0]);
        printf("\n");
    }
    _endthread();
}

int _tmain(int argc, _TCHAR* argv[])
{
    WORD version;
    WSADATA wsaData;
    int result;
    version = MAKEWORD(2,2);
    WSAStartup(version,(LPWSADATA)&wsaData);

    LPHOSTENT hostEntry;
    hostEntry = gethostbyname("127.0.0.1");
    if(!hostEntry)
    {
        printf ("%s", "  >>> ERROR  (hostEntry NULL)\n");
        WSACleanup();
        return CS_ERROR;
    }

    SOCKET theSocket = socket(AF_INET, SOCK_STREAM, 0);
    if(theSocket == SOCKET_ERROR)
    {
        printf ("%s", "  ERROR  (can't create socket)\n");
        return CS_ERROR;
    }
    else
    {
        printf ("%s", "  >>> Creating socket \n");
    }

    sockaddr_in serverInfo;
    serverInfo.sin_family = AF_INET;
    serverInfo.sin_addr = *((LPIN_ADDR)*hostEntry->h_addr_list);
    serverInfo.sin_port = htons(8888);

    result=connect(theSocket,(LPSOCKADDR)&serverInfo,
    sizeof(serverInfo));
    if(result==SOCKET_ERROR)
    {
        printf ("%s", "  ERROR (can't connect to Server)\n");
        return CS_ERROR;
    }
    else
    {
        printf ("%s", "  >>> Connecting to Server\n");
    }
    printf("Write a message: ");
    scanf_s("%s", send_buf, sizeof(send_buf));
    _beginthread(MyFunction,0,(void *)&theSocket);
    char a[100];
    scanf_s("%s", a, sizeof(a));
    return CS_OK;
}

I suppose it has something to do with accessing send_buf\recv_buf in illegal way, but I can't figure what. Any tips?

War es hilfreich?

Lösung

You're not calling scanf_s properly. scanf_s requires two arguments for string input - one with the pointer to the string, and another for the maximum length of the string.

So you should call it like this:

scanf_s("%s", send_buf, sizeof(send_buf));
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top