wsxiot的博客

IT民工搬砖记录

Windows下使用Codeblocks写c语言socket

如何在Windows下使用Codeblocks写c语言socket

  • 首先新建一个工程
  • 然后右键点击工程名称->Build options->Linker setting
    • 在Link libraries->add->在codeblocks安装路径下MinGW\lib下找到libwsock32.a,加入工程
    • 在Other linker options下加入-lwsock32
  • 书写符合winsock语法要求的代码运行

    示例udp代码

  • server
#include <WINSOCK2.H>
#include <stdio.h>
#include <string.h>
#include <time.h>
int main()
{
    WSADATA wsaData;
    WORD versionRequired=MAKEWORD(1,1);
    WSAStartup(versionRequired,&wsaData);
    SOCKET sock_fd;
    SOCKADDR_IN  servaddr;
    SOCKADDR_IN  cliaddr;
    int len = sizeof(cliaddr);
    char buff[1024];
    time_t timep;
    int i = 0;
    sock_fd = socket(PF_INET,SOCK_DGRAM,0);
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(6666);
    servaddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
    memset(buff,0,sizeof(buff));
    bind(sock_fd, (SOCKADDR *)&servaddr, sizeof(servaddr));
    while(1)
    {
        memset(buff,0,sizeof(buff));
        recvfrom(sock_fd,buff,sizeof(buff),0,(struct sockaddr *)&cliaddr,&len);
        time(&timep);
        sprintf(buff, "%s",  ctime(&timep));
        sendto(sock_fd, buff, strlen(buff)-1, 0, (struct sockaddr *)&cliaddr, sizeof(servaddr));
        printf("%s%d\n", buff,i++);
    }
    closesocket(sock_fd);
    WSACleanup();
    return 0;
}
  • client
#include <WINSOCK2.H>
#include <stdio.h>
#include <string.h>
int main()
{
    WSADATA wsaData;
    WORD versionRequired=MAKEWORD(1,1);
    WSAStartup(versionRequired,&wsaData);//协议库的版本信息
    SOCKET sock_fd;
    SOCKADDR_IN  servaddr;
    char buff[100];
    const char *str = "gettime";
    const char *serverip = "127.0.0.1";
    short port = 6666;
    sock_fd = socket(PF_INET,SOCK_DGRAM,0);
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(port);
    servaddr.sin_addr.S_un.S_addr = inet_addr(serverip);
    memset(buff,0,sizeof(buff));
    sendto(sock_fd, str, strlen(str), 0, (struct sockaddr *)&servaddr, sizeof(servaddr));
    recvfrom(sock_fd, buff, sizeof(buff), 0, NULL, NULL);
    printf("%s\n",buff);
    closesocket(sock_fd);
    WSACleanup();
    return 0;
}
阅读更多
版权声明:如有侵权,请联系,如有错误,望指正,欢迎转载 https://blog.csdn.net/qq_29630271/article/details/72983773
文章标签: socket winsock2
个人分类: c/c++
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭