C ++在发送结构时使用UDP套接字发送操作时出错

时间:2015-02-12 03:28:59

标签: c++ sockets struct udp udpclient

我一直在忙着this code尝试发送除字符数组之外的其他内容。我创建了一个struct Packet,但是我得到的类型' Packet ''与' const char '"类型的参数不兼容错误。

当我尝试将struct Packet传递给sendto方法时,会发生这种情况。我包含了所有客户端代码,因此您可以更好地了解正在发生的事情。带有错误的行是唯一对其进行注释以便于查找的内容。它处于while循环中,我现在可能不再需要了,但这只是练习代码。

#include<stdio.h>
#include<winsock2.h>
#include <sstream>
#include <string.h>

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

#define SERVER "127.0.0.1"  //ip address of udp server
#define BUFLEN 512  //Max length of buffer
#define PORT 8888   //The port on which to listen for incoming data

using namespace std;

struct Packet
{
    int id;
    int number;
};

int main(void)
{
    struct sockaddr_in si_other;
    int s, slen=sizeof(si_other);
    char buf[BUFLEN];
    WSADATA wsa;

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

    if ( (s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == SOCKET_ERROR)
    {
        printf("socket() failed with error code : %d" , WSAGetLastError());
        exit(EXIT_FAILURE);
    }

    memset((char *) &si_other, 0, sizeof(si_other));
    si_other.sin_family = AF_INET;
    si_other.sin_port = htons(PORT);
    si_other.sin_addr.S_un.S_addr = inet_addr(SERVER);

    while(1)
    {    
        system("pause");

        struct Packet *thing = new Packet();

        thing->id= htonl(1000);
        thing->number= htonl(7788);

        //*************************************
        //The error is with thing in the sendto statement.
        if (sendto(s, thing, sizeof(*thing) , 0 , (struct sockaddr *) &si_other, slen) == SOCKET_ERROR)
        {
            printf("sendto() failed with error code : %d" , WSAGetLastError());
            exit(EXIT_FAILURE);
        }

        memset(buf,'\0', BUFLEN);
        if (recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen) == SOCKET_ERROR)
        {
            printf("recvfrom() failed with error code : %d" , WSAGetLastError());
            exit(EXIT_FAILURE);
        }

        puts(buf);
    }

    closesocket(s);
    WSACleanup();

    return 0;
}

0 个答案:

没有答案