Windows下客户端编程

#include <stdio.h>
#include <string.h>
#include <winsock2.h>

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

#define SERVER_PORT 20000          /* 端口 */
static char *server = "192.168.1.26";             /* 服务器地址 */

int main(int argc, char* argv[])
{
  struct sockaddr_in addr;        /* 服务器端地址结构 */
  SOCKET sock;                                /* 与服务器端通信的套接字 */
  int sen = 0;
  int ret = 0;

  char recvbuf[1024] = "";

  /* 指明套接字版本 */
  WORD wVersion = MAKEWORD(2, 2);
  WSADATA wsData;
  int nResult = WSAStartup(wVersion, &wsData);
  if(nResult != 0)
  {
    return;
  }

        /* 创建客户端套接字 */
        if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
  {
    printf("Create socket error!\n");
    return;
  }

  /* 填充地址结构 */
  memset(&addr, 0, sizeof(addr));
  addr.sin_family = AF_INET;                                                            /* 地址簇 */
  addr.sin_addr.S_un.S_addr = inet_addr("192.168.1.26");    /* 服务器IP地址 */
  addr.sin_port = htons(SERVER_PORT);                                         /* 端口 */

  /* 连接到服务器 */
  if (connect(sock,(struct sockaddr *)&addr, sizeof(addr)) == -1)
  {
    printf("Connect to server error!\n");
    return;
  }

  /* 往服务器端发送字符串 */
  /*
  if ((ret = send(sock, sendbuf, 1024, 0)) < 0)
  {
    printf("Send data error!\n");
    return;
  }
  */
    
  memset(recvbuf, 0, sizeof(recvbuf));

  /* 从服务器端接收字符串 */
  if ((sen = recv(sock, recvbuf, 1024, 0)) < 0)
  {
    printf("Receive data error!\n");
    return;
  }

  printf("Receive data : %s \n", recvbuf);

  closesocket(sock);
  WSACleanup();
  return 0;
}

你可能感兴趣的:(socket,职场,休闲,客户端编程)