admin 管理员组

文章数量: 887021

一、介紹
有時候需要用windows写点小工具需要用到tcpip,这里介绍在dev c++下编写UDP网络通信

流程和linux差不多
使用WSAStartup()函数检查系统协议栈安装情况
使用socket()函数创建服务器端通信套接字
使用sendto()函数发送数据,
使用recvfrom()函数接收数据
使用closesocket()函数关闭套接字
最后调用WSACleanup()函数结束Winsock Sockets API

二、工程配置
添加库libws2_32.a

三、udp源代码
udp.c

#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32")

static SOCKET Udp;

int udp_init(char *ip, int port)
{
    struct sockaddr_in ser; //服务器端地址
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
    {
        printf("Failed to load Winsock.\n"); //Winsock 初始化错误
        return -1;
    }
    ser.sin_family = AF_INET;                       //初始化服务器地址信息
    ser.sin_port = htons(port);                     //端口转换为网络字节序
    ser.sin_addr.s_addr = inet_addr(ip);            //IP 地址转换为网络字节序
    Udp = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); //创建UDP套接字
    if (Udp == INVALID_SOCKET)
    {
        printf("socket() Failed: %d\n", WSAGetLastError());
        return -1;
    }
    if (bind(Udp, (LPSOCKADDR)&ser, sizeof(ser)) == SOCKET_ERROR)
    {
        printf("绑定IP和端口\n");
        return 0;
    }
    printf("udp init ok\n");
}

int udp_send(char *ip, int port, unsigned char *buff, int len)
{
    struct sockaddr_in s;
    int ret,addrlen;

    s.sin_family = AF_INET;
    s.sin_port = htons(port);
    s.sin_addr.s_addr = inet_addr(ip);
    addrlen = sizeof(s);
    sendto(Udp, buff, len, 0, (SOCKADDR *)&s, addrlen);

    return 0;
}

int udp_rcv(char *ip, int *port, unsigned char *buff, int *len)
{
    struct sockaddr_in s;
    int ret,addrlen;

    addrlen = sizeof(s);
    ret = recvfrom(Udp, buff, 1024, 0, (SOCKADDR *)&s, &addrlen);
    if (ret > 0)
    {
        memcpy(ip, inet_ntoa(s.sin_addr), strlen(inet_ntoa(s.sin_addr)));//copy ip to from_ip
        *port = ntohs(s.sin_port);
       // printf("rcv ok\n");
    }
    *len = ret;
    
    return ret;
}

int close_udp()
{
    closesocket(Udp); //关闭 socket
    WSACleanup();
}

udp.h

#ifndef __UDP_H
#define __UDP_H

int udp_init(char *ip, int port);
int udp_send(char *ip, int port, unsigned char *buff, int len);
int udp_rcv(char *ip, int *port, unsigned char *buff, int *len);
int close_udp();

#endif

main.c

#include <stdio.h>
#include "udp.h"
i
nt udp_test()
{
    unsigned char buff[1024] = {0};
    int rcv_len;
    char ip[25] = {0};
    int port;

    printf("udp_test\n");
    udp_init("192.168.3.65", 3000);

    while(1)
    {
        if(udp_rcv(ip, &port, buff, &rcv_len) > 0)
        {
            printf("rcv ip:%s,port:%d,rcvlen:%d,data:%s", ip, port, rcv_len, buff);
            udp_send("192.168.3.65", 1000, buff, rcv_len);     
        }
    }
}

int main(int argc, char *argv[])
{
    //tcp_server_test();
    udp_test();
    return 0;
}

四、结果

本文标签: 通信 Windows UDP