在套接字程序中调用API?

时间:2014-01-27 14:40:12

标签: c api sockets operating-system ip

void CreateSocket()
{
struct sockaddr_in server, client;  // creating a socket address structure: structure contains ip address and port number
WORD wVersionRequested;
WSADATA wsaData;
int len;
int iResult;

    printf("Initializing Winsock\n");


    wVersionRequested = MAKEWORD (1, 1);
    iResult =  WSAStartup (wVersionRequested, &wsaData);      
    if (iResult != NO_ERROR)
   printf("Error at WSAStartup()\n"); 


    // create socket
    sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (sock < 0)    {
        printf("Could not Create Socket\n");
        //return 0;
    }

    printf("Socket Created\n");  


    // create socket address of the server
    memset( &server, 0, sizeof(server));


    // IPv4 - connection
    server.sin_family = AF_INET;
    // accept connections from any ip adress
    server.sin_addr.s_addr = htonl(INADDR_ANY);
    // set port
    server.sin_port = htons(52428);


    //Binding between the socket and ip address
    if(bind (sock, (struct sockaddr *)&server, sizeof(server)) < 0)
    {
        printf("Bind failed with error code: %d", WSAGetLastError());
    }


    //Listen to incoming connections
    if(listen(sock, 3) == -1){
        printf("Listen failed with error code: %d", WSAGetLastError());
    }

    printf("Server has been successfully set up - Waiting for incoming connections");

        len = sizeof(client);
        fd = accept(sock, (struct sockaddr*) &client, &len);

        if(fd < 0)
        {
            printf("Accept failed\n");
        }
        printf("\n Process incoming connection from (%s , %d)", inet_ntoa(client.sin_addr),ntohs(client.sin_port));



}


int main()
{

    HANDLE h1,h2,h3;



double Task2ms_Raster, Task10ms_Raster, Task100ms_Raster ;


CreateSocket();

 Xcp_Initialize();

     while(1)
        {
        if(fd == -1)
        {
            printf("Socket error\n ");
        }
        else

        {
             recv(fd, recv_data, 99, 0);
            //  pChunkData = &recv_data;
            //chunkLen = sizeof(pChunkData);
            //XcpIp_RxCallback ((uint16) chunkLen, (char*) pChunkData, (uint16) port);

        }
        }


        }

以上是服务器程序: 我正在创建一个带有IP地址和端口号的套接字。我接受来自客户端的连接并从客户端接收数据。我必须调用API:XcpIp_RxCallback((uint16)chunkLen,(char *)pChunkData,(uint16)port);当它在端口上接收数据时。谁能告诉我在上面的程序中调用API的位置?

1 个答案:

答案 0 :(得分:0)

使用recvfrom函数http://msdn.microsoft.com/en-us/library/windows/desktop/ms740120%28v=vs.85%29.aspx然后调用XcpIp_RxCallback

代码看起来像

 iResult = recvfrom(RecvSocket,RecvBuf, 
     BufLen, 0, (SOCKADDR *) & SenderAddr, &SenderAddrSize);

 if (iResult == SOCKET_ERROR) {
     wprintf(L"recvfrom failed with error %d\n", WSAGetLastError());
 } else {
     XcpIp_RxCallback ((uint16) iResult, (char*) RecvBuf, (uint16)htons(SenderAddr.sin_port));
 }