cygwin(windows)和gcc / g ++ mac中的udp客户端服务器

时间:2012-12-06 00:58:03

标签: c++ macos udp cygwin client-server

我是网络初学者。我有计划使用pc(window xp)作为客户端和mac作为服务器来创建客户端服务器udp。我已经制作了server.cc,client.cc,net.h和makefile配置。

我使用cygwin在窗口中制作文件,使用g ++制作mac。

但是当我在cygwin中创建文件时出现错误:

g ++ -c -o server.o server.cc

CC -o udp_server server.o -lsocket -lnsl

/usr/lib/gcc/i686-pc-cygwin/4.5.3 /../../../../ i686-pc-cygwin / bin / ld:找不到-lsocket

/usr/lib/gcc/i686-pc-cygwin/4.5.3 /../../../../ i686-pc-cygwin / bin / ld:找不到-lnsl collect2:ld返回1退出状态

并在mac中错误是:

c ++ -c -o server.o server.cc

CC -o udp_server server.o -lsocket -lnsl

ld:找不到-lsocket的库 clang:错误:链接器命令失败,退出代码为1(使用-v查看调用)

这是我服务器的代码程序:

#include "net.h"
#include <iostream> //diilangin .h
using namespace std; //ditambah

const int  kWELL_KNOWN_PORT = 49998;
const char kMESSAGE[]  = "UDP Bye";

int main(){

// our to be server end-point, and client endpoint
   struct sockaddr_in serv_addr;
   struct sockaddr_in cli_addr;
   int cli_sock = 0, retval = 0; 

// need to first ask OS for free socket descriptor
// this will be the listening socket - notr SOCK_DGRAM option now
   cli_sock = socket(AF_INET, SOCK_DGRAM, 0);
   if(cli_sock<0)
  cerr<<"Error when trying to create socket"<<strerror(errno)<<endl;
   else {
  // build an internet socket address structure, defining port.
  memset(&serv_addr, 0, sizeof(serv_addr));
  serv_addr.sin_family      = AF_INET;
  serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); // any of this machines IPs will do
  serv_addr.sin_port        = htons(kWELL_KNOWN_PORT);

  // attempt to bind socket - still need to in UDP
  retval = bind(cli_sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
  if(retval < 0)
     cerr<<"Could not bind to port"<<endl<<strerror(errno)<<endl;
  else {
     // forever loop no more accept or listen!!!
     for(;;) {
        char buff[256];

        // get the message and display it
        //int clilen = sizeof(cli_addr); di comment
        socklen_t clilen = (socklen_t)sizeof(cli_addr);
        int len = recvfrom(cli_sock, buff, 256, 0, (struct sockaddr*)&cli_addr, &clilen);
        buff[len] = 0;
        cout<<"GOT "<<buff<<endl;

        // send a reply
        strcpy(buff,kMESSAGE);
        if(sendto(cli_sock, buff, strlen(buff), 0, (struct sockaddr*)&cli_addr, clilen) == -1)
           cerr<<"Error when sending"<<endl<<strerror(errno)<<endl;
     }
      }
   }
   return 0;
} 

有人建议改进我的课程吗?

丹尼尔

1 个答案:

答案 0 :(得分:0)

cygwin上没有-lsocket(libsocket)。你能尝试添加:

#include <sys/socket.h>

...到你的标题? sys / socket.h是Cygwin的标准配置。

我希望这有用!