C语言实现windows和linux下socket通信

client connect to the IP and Port that bind with server

server bind a IP and Port

then client connect the IP and Port

//client
/*if happend error: error C4996: 'inet_addr': Use inet_pton() or InetPton() instead 
    or define _WINSOCK_DEPRECATED_NO_WARNINGS to disable deprecated API warnings

Slove:  Project properties -> Configuration Properties -> C/C++ -> General -> SDL checks -> No
*/

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>

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

#define DES_IP "127.0.0.1"  
#define DES_PORT 5000

int main()
{
    SOCKET sock;
    char buf[1024];
    SOCKADDR_IN ser_addr;
    WSADATA wsaData;
    WORD wVersionRequired;
    wVersionRequired = MAKEWORD(2, 2);
    if (WSAStartup(wVersionRequired, &wsaData)!= 0)
    {
        printf("init failed %ld\n",WSAGetLastError());

        //  return 1;
    }

    //create socket
    sock = socket(AF_INET, SOCK_STREAM, 0);

    ser_addr.sin_addr.S_un.S_addr = inet_addr(DES_IP);  //127.0.0.1
    ser_addr.sin_port = htons(DES_PORT);                //5000
    ser_addr.sin_family = AF_INET;
    memset(ser_addr.sin_zero, 0, 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值