zoukankan      html  css  js  c++  java
  • c/c++ 网络编程 bind函数

    网络编程 bind函数

    bind的作用是确定端口号。

    正常处理都是先bind,然后listen

    如果不bind,直接listen,会是什么结果?

    内核会自动随机分配一个端口号

    例子:

    #include <iostream>
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <unistd.h>
    #include <arpa/inet.h>
    #include <netinet/in.h>
    
    void print_ip_port(int sock){
      char buf[48];
      sockaddr_in s;
      socklen_t sz;
    
      sz = sizeof(s);
    
      //取得socket里面的ip地址和端口号
      if(getsockname(sock, (sockaddr*)&s, &sz) != 0){
        perror("getsockname");
        return;
      }
    
      //把bind的ip转化成字符串
      inet_ntop(AF_INET, &s.sin_addr, buf, sizeof(buf));
      std::cout << buf << ":" << ntohs(s.sin_port) << std::endl;
    }
    int main(){
      int s0, sock;
      sockaddr_in peer;
      socklen_t peerlen;
      int n;
      char buf[1024];
    
      //socket创建成功后,马上就调用监听listen
      s0 = socket(AF_INET,SOCK_STREAM,0);
      if(listen(s0, 5) != 0){
        perror("listen");
        return 1;
      }
    
      //打印出ip地址和端口号
      print_ip_port(s0);
    
      //等待客户端的连接
      peerlen = sizeof(peer);
      sock = accept(s0, (sockaddr*)&peer, &peerlen);
      if(sock < 0){
        perror("accept");
        return 1;
      }
    
      write(sock, "hello
    ", 6);
    
      close(s0);
      close(sock);
      
    }
    
    

    github源代码

    c/c++ 学习互助QQ群:877684253

    本人微信:xiaoshitou5854

  • 相关阅读:
    1JavaScript的历史
    扯扯 require .js
    查看js 执行效率工具
    php 输入输出流
    词法分析096
    Python基础综合练习
    096
    大数据概述
    熟悉常用的Linux操作
    实验一、词法分析实验
  • 原文地址:https://www.cnblogs.com/xiaoshiwang/p/9758308.html
Copyright © 2011-2022 走看看