简体   繁体   中英

Winsock send () over TCP in C

I'm just confusing using the send() function in Winsock. Does this code actually send a string "Hello" over TCP ?. I managed to establish a connection with a TCP client in LabVIEW but it seems like that this TCP server doesn't send anything.

#define DEFAULT_BUFLEN 1024

#include<stdio.h>
#include<winsock2.h>
#include<Ws2tcpip.h>
#include<stdlib.h>
#include<string.h>
#include<stdint.h>
#include<stddef.h>

#pragma comment(lib,"ws2_32.lib") //Winsock Library

int main(int argc , char *argv[])
{
WSADATA wsa;
SOCKET s , new_socket;
struct sockaddr_in server , client;
int c;
int iResult;
char *sendbuf = "Hello";


printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
  {
    printf("Failed. Error Code : %d",WSAGetLastError());
    return 1;
  }

printf("Initialised.\n");

//Create a socket
if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
  {
    printf("Could not create socket : %d" , WSAGetLastError());
  }

printf("Socket created.\n");

//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 13000 );

//Bind
if( bind(s ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR)
  {
    printf("Bind failed with error code : %d" , WSAGetLastError());
  }

puts("Bind done");

//Listen to incoming connections
listen(s , 3);

//Accept and incoming connection
puts("Waiting for incoming connections...");

c = sizeof(struct sockaddr_in);
new_socket = accept(s , (struct sockaddr *)&client, &c);
if (new_socket == INVALID_SOCKET)
  {
    printf("accept failed with error code : %d" , WSAGetLastError());
  }

iResult = send( new_socket, sendbuf, (int)strlen(sendbuf), 0 );

if (iResult == SOCKET_ERROR) 
{
    wprintf(L"send failed with error: %d\n", WSAGetLastError());
    closesocket(new_socket);
    WSACleanup();
    return 1;
}
printf("Bytes Sent: %d\n", iResult);

// shutdown the connection since no more data will be sent
iResult = shutdown(new_socket, SD_SEND);
if (iResult == SOCKET_ERROR) 
  {
    wprintf(L"shutdown failed with error: %d\n", WSAGetLastError());
    closesocket(new_socket);
    WSACleanup();
    return 1;
  }
}

Your code is not initialzing WinSock, not allocating any SOCKET object, and not establishing a connection between the socket and a peer before calling send() , so to answer your question:

NO , your code is NOT sending a string over TCP.

HOWEVER , if you fill in the missing pieces - call socket() to create a TCP socket, and call bind()/listen()/accept() to establish a TCP connection with a peer - then YES , your code will be sending the string over TCP.

You need to do something more like the following instead. This is just a simple example that establishes a single TCP connection and then exits once the string has been sent to the client. In a real-world application, you would need to leave the server socket open and continuously calling accept() if you want to service multiple client connections over time, even if just a single client ever connects, disconnects, and reconnects:

int main(int argc , char *argv[])
{
    WSADATA wsa;
    SOCKET server_socket, client_socket;
    struct sockaddr_in server_addr, client_addr;
    int iResult;
    char *sendbuf = "Hello";

    iResult = WSAStartup(MAKEWORD(2, 0), &wsa);
    if (iResult != 0)
    {
        wprintf(L"WinSock startup failed with error: %d\n", iResult);
        return 1;
    }

    server_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (server_socket == INVALID_SOCKET) 
    {
        wprintf(L"socket failed with error: %d\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }

    memset(&server_addr, 0, sizeof(server_addr);
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(some port number here);
    server_addr.sin_addr.s_addr = INADDR_ANY;

    if (bind(server_socket, (sockaddr*)&server_addr, sizeof(server_addr)) != 0)
    {
        wprintf(L"bind failed with error: %d\n", WSAGetLastError());
        closesocket(server_socket);
        WSACleanup();
        return 1;
    }

    if (listen(server_socket, 1) != 0)
    {
        wprintf(L"listen failed with error: %d\n", WSAGetLastError());
        closesocket(server_socket);
        WSACleanup();
        return 1;
    }

    iResult = sizeof(client_addr);
    client_socket = accept(server_socket, (sockaddr*)&client_addr, &iResult);
    if (client_socket == SOCKET_ERROR)
    {
        wprintf(L"accept failed with error: %d\n", WSAGetLastError());
        closesocket(server_socket);
        WSACleanup();
        return 1;
    }

    closesocket(server_socket);

    iResult = send(client_socket, sendbuf, strlen(sendbuf), 0);
    if (iResult == SOCKET_ERROR) 
    {
        wprintf(L"send failed with error: %d\n", WSAGetLastError());
        closesocket(client_socket);
        WSACleanup();
        return 1;
    }

    printf("Bytes Sent: %d\n", iResult);

    closesocket(client_socket);
    WSACleanup();
    return 0;
}

Update : based on your updated code, try this:

#include <stdio.h>
#include <winsock2.h>
#include <Ws2tcpip.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stddef.h>

#pragma comment(lib, "ws2_32.lib") //Winsock Library

int main(int argc , char *argv[])
{
    WSADATA wsa;
    SOCKET server_socket, client_socket;
    struct sockaddr_in server_addr, client_addr;
    int c, iResult;
    char *sendbuf = "Hello";

    printf("Initializing Winsock...\n");

    iResult = WSAStartup(MAKEWORD(2,2), &wsa);
    if (iResult != 0)
    {
        printf("WinSock initialization Failed. Error Code : %d", iResult);
        return 1;
    }

    printf("WinSock Initialized.\n");

    //Create a socket
    s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (s == INVALID_SOCKET)
    {
        printf("Could not create socket. Error Code : %d" , WSAGetLastError());
        WSACleanup();
        return 1;
    }

    printf("Socket created.\n");

    //Prepare the sockaddr_in structure
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons( 13000 );

    //Bind the listening port
    if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == SOCKET_ERROR)
    {
        printf("Bind failed. Error Code : %d", WSAGetLastError());
        closesocket(server_socket);
        WSACleanup();
        return 1;
    }

    printf("Socket bound to port 13000.\n");

    //Listen to incoming connection
    if (listen(server_socket, 1) == SOCKET_ERROR)
    {
        printf("Listen failed. Error Code : %d", WSAGetLastError());
        closesocket(server_socket);
        WSACleanup();
        return 1;
    }

    //Accept an incoming connection
    printf("Waiting for incoming connection...\n");

    c = sizeof(client_addr);
    client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &c);
    if (client_socket == INVALID_SOCKET)
    {
        printf("Accept failed. Error Code : %d", WSAGetLastError());
        closesocket(server_socket);
        WSACleanup();
        return 1;
    }

    printf("Client connected from %s:%hu\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));

    //Stop accepting incoming connections
    closesocket(server_socket);

    // Send string to client
    iResult = send(client_socket, sendbuf, strlen(sendbuf), 0);
    if (iResult == SOCKET_ERROR) 
    {
        printf("Send failed. Error Code : %d\n", WSAGetLastError());
        iResult = 1;
    }
    else
    {
        printf("Bytes Sent: %d\n", iResult);
        iResult = 0;
    }

    // shutdown the connection since no more data will be sent
    if (shutdown(client_socket, SD_SEND) == SOCKET_ERROR) 
    {
        printf("Shutdown failed. Error Code : %d\n", WSAGetLastError());
        iResult = 1;
    }

    closesocket(client_socket);
    WSACleanup();

    return iResult;
} 

No, it does not send the string "Hello". Even if the socket bind/accept/etc connection is OK, 'send(client_socket, sendbuf, strlen(sendbuf), 0);' does not send a C string. It sends five bytes, whereas the the C string "Hello" requires six bytes. Try:

send(client_socket, sendbuf, 1+strlen(sendbuf), 0);

A very high percentage of networking C code problems can be found by searching the source text for 'strlen'. printf(%s..), and assuming that TCP transfers messages longer than one byte, accounts for the rest:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM