windows vc++ vs winsock2.h socket通信

时间:2020-08-01
本文章向大家介绍windows vc++ vs winsock2.h socket通信,主要包括windows vc++ vs winsock2.h socket通信使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

sendto

int sendto(
  SOCKET         s,
  const char     *buf,
  int            len,
  int            flags,
  const sockaddr *to,
  int            tolen
);

这个使用时需要这样来用。特别是最后的tolen,必须得是一个int参数,不能用sizeof。

int addrsize = sizeof(addrto);
int len = sendto(sock, message, BUF_SIZE, 0, (SOCKADDR*)&addrto, addrsize);
if (len == SOCKET_ERROR)
    printf("recvfrom err = %d\n", WSAGetLastError());

比如下面的用法就不行。原因不知道。

int len = sendto(sock, message, BUF_SIZE, 0, (SOCKADDR*)&addrto, sizeof(addrsize));

recv和recvfrom

recv用于tcp的stream流。recvfrom用于udp。

完整代码

不知为何,只是接收不行,需要先发送一个数据才能接收?

#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <stdio.h>
#include <winsock2.h>
#include <ws2ipdef.h>
#include <ws2tcpip.h>
#include <wsipv6ok.h>


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

#define BUF_SIZE 500
#define _WINSOCK_DEPRECATED_NO_WARNINGS

int iResult = 0;
WSADATA wsaData;
SOCKET sock;
char message[BUF_SIZE] = "send...";
SOCKADDR_IN6 addrto, addrfrom;
char rcvbuf[BUF_SIZE];

typedef struct {
    unsigned char ver : 2;
    unsigned char tp_type : 1;
    unsigned char ackflag : 1;
    unsigned char res1 : 4;
    unsigned char seq;
    unsigned char ackseq;
    unsigned char res2;
}secondhdr_t;

secondhdr_t sechdr;
unsigned char sequence = 0;

int main(int argc, char * argv[])
{
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);

    sock = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);    /*需要管理员权限*/
    if (sock == INVALID_SOCKET)
        printf("sock err = %d\n", WSAGetLastError());

    addrfrom.sin6_family = AF_INET6;
    iResult = inet_pton(AF_INET6, "fc00::d41:0:0:d41:2", addrfrom.sin6_addr.u.Byte);
    addrfrom.sin6_port = htons(2020);
    addrfrom.sin6_scope_id = 0;

    addrto.sin6_family = AF_INET6;
    iResult = inet_pton(AF_INET6, "fc00::d41:0:0:d41:1", addrto.sin6_addr.u.Byte);
    addrto.sin6_port = htons(2020);
    addrto.sin6_scope_id = 0;

    iResult = bind(sock, (SOCKADDR *)&addrfrom, sizeof(addrfrom));
    if (iResult == SOCKET_ERROR)
        printf("bind err = %d\n", WSAGetLastError());

    int addrsize = sizeof(addrto);
    int len = sendto(sock, message, BUF_SIZE, 0, (SOCKADDR*)&addrto, addrsize);
    if (len == SOCKET_ERROR)
        printf("recvfrom err = %d\n", WSAGetLastError());

    while (1)
    {
        addrsize = sizeof(addrfrom);
        len = recvfrom(sock, rcvbuf, BUF_SIZE, 0, (SOCKADDR*)&addrfrom, &addrsize);
        if(len == SOCKET_ERROR)
            printf("recvfrom err = %d\n", WSAGetLastError());
        for (int i = 0; i < 10; i++)
        {
            printf("%X ", rcvbuf[i]);
        }
        printf("\nlen=%d\n", len);
    }
}
View Code

 

$flag 上一页 下一页