关闭

Windows下使用Codeblocks写c语言socket

标签: socketwinsock2
231人阅读 评论(0) 收藏 举报
分类:

如何在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;
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:24600次
    • 积分:838
    • 等级:
    • 排名:千里之外
    • 原创:60篇
    • 转载:6篇
    • 译文:0篇
    • 评论:7条
    文章分类
    最新评论