网络设备驱动(3)

本人电路板使用的网卡为CS8900,鉴于其datasheet过于庞大没有做深究只是了解了一下其IO模式。其驱动程序如下
#include <linux/config.h>
#include <linux/version.h>
#include <linux/module.h>

#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/delay.h>

#include <asm/irq.h>
#include <asm/hardware.h>
#include <asm/io.h>
#include <asm/arch/regs-gpio.h>

#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>

#include "cirrus.h"

#if 0
//#elif CONFIG_ARCH_CSB226
# define CIRRUS_DEFAULT_IO 0xF8000300
# define CIRRUS_DEFAULT_IRQ IRQ_GPIO(16)
 /* PTX: uggly hack... */
# define CS8900_OFF 0x04
# define CS8900_PPTR *(volatile u32 *)(CIRRUS_DEFAULT_IO+0x05*CS8900_OFF)
# define CS8900_PDATA *(volatile u32 *)(CIRRUS_DEFAULT_IO+0x06*CS8900_OFF)
//#else
# define CIRRUS_DEFAULT_IO 0
# define CIRRUS_DEFAULT_IRQ 0
#endif

typedef struct {
 struct net_device_stats stats;//状态结构
 u16 txlen;
 int char_devnum;

  spinlock_t lock;
} cirrus_t;

typedef struct {
 u16 io_base;  /* I/O Base Address   */
 u16 irq;   /* Interrupt Number   */
 u16 dma;   /* DMA Channel Numbers  */
 u32 mem_base;  /* Memory Base Address  */
 u32 rom_base;  /* Boot PROM Base Address */
 u32 rom_mask;  /* Boot PROM Address Mask */
 u8 mac[6];   /* Individual Address  */
} cirrus_eeprom_t;

/*
 * I/O routines
 */

static inline u16 cirrus_read (struct net_device *dev,u16 reg)
{
 CIRRUS_outw (reg, dev->base_addr, PP_Address);
 return (CIRRUS_inw (dev->base_addr, PP_Data));
}

static inline void cirrus_write (struct net_device *dev,u16 reg,u16 value)
{
 CIRRUS_outw (reg, dev->base_addr, PP_Address);
 CIRRUS_outw (value, dev->base_addr, PP_Data);
}

static inline void cirrus_set (struct net_device *dev,u16 reg,u16 value)
{
 cirrus_write (dev,reg,cirrus_read (dev,reg) | value);
}

static inline void cirrus_clear (struct net_device *dev,u16 reg,u16 value)
{
 cirrus_write (dev,reg,cirrus_read (dev,reg) & ~value);
}

static inline void cirrus_frame_read (struct net_device *dev,struct sk_buff *skb,u16 length)
{
 CIRRUS_insw (dev->base_addr, 0, skb_put (skb,length), (length + 1) / 2);
}

static inline void cirrus_frame_write (struct net_device *dev,struct sk_buff *skb)
{
 CIRRUS_outsw (dev->base_addr, 0, skb->data, (skb->len + 1) / 2);//使用port0读写数据包
}

/*
 * Debugging functions
 */

#ifdef DEBUG
static inline int printable (int c)
{
 return ((c >= 32 && c <= 126) ||
   (c >= 174 && c <= 223) ||
   (c >= 242 && c <= 243) ||
   (c >= 252 && c <= 253));
}

static void dump16 (struct net_device *dev,const u8 *s,size_t len)
{
 int i;
 char str[128];

 if (!len) return;

 *str = '/0';

 for (i = 0; i < len; i++) {
  if (i && !(i % 4)) strcat (str," ");
  sprintf (str,"%s%.2x ",str,s[i]);
 }

 for ( ; i < 16; i++) {
  if (i && !(i % 4)) strcat (str," ");
  strcat (str,"   ");
 }

 strcat (str," ");
 for (i = 0; i < len; i++) sprintf (str,"%s%c",str,printable (s[i]) ? s[i] : '.');

 printk (KERN_DEBUG "%s:     %s/n",dev->name,str);
}

static void hexdump (struct net_device *dev,const void *ptr,size_t size)
{
 const u8 *s = (u8 *) ptr;
 int i;
 for (i = 0; i < size / 16; i++, s += 16) dump16 (dev,s,16);
 dump16 (dev,s,size % 16);
}

static void dump_packet (struct net_device *dev,struct sk_buff *skb,const char *type)
{
 printk (KERN_INFO "%s: %s %d byte frame %.2x:%.2x:%.2x:%.2x:%.2x:%.2x to %.2x:%.2x:%.2x:%.2x:%.2x:%.2x type %.4x/n",
   dev->name,
   type,
   skb->len,
   skb->data[0],skb->data[1],skb->data[2],skb->data[3],skb->data[4],skb->data[5],
   skb->data[6],skb->data[7],skb->data[8],skb->data[9],skb->data[10],skb->data[11],
   (skb->data[12] << 8) | skb->data[13]);
 if (skb->len < 0x100) hexdump (dev,skb->data,skb->len);
}
#endif /* #ifdef DEBUG */

/*
 * Driver functions
 */

static void cirrus_receive (struct net_device *dev)//读取数据到套接字缓冲
{
 cirrus_t *priv = (cirrus_t *) dev->priv;
 struct sk_buff *skb;
 u16 status,length;

 status = cirrus_read (dev,PP_RxStatus);//读取数据包状态
 length = cirrus_read (dev,PP_RxLength);//读取数据包长度

 if (!(status & RxOK)) {//出错
  priv->stats.rx_errors++;
  if ((status & (Runt | Extradata))) priv->stats.rx_length_errors++;
  if ((status & CRCerror)) priv->stats.rx_crc_errors++;
  return;
 }

 if ((skb = dev_alloc_skb (length + 4)) == NULL) {//建立套接字缓冲区和数据缓冲区
  priv->stats.rx_dropped++;
  return;
 }

 skb->dev = dev;
 skb_reserve (skb,2);//将data下移2,以便IP头16B对齐

 cirrus_frame_read (dev,skb,length);//将数据复制到缓冲区中

#ifdef DEBUG
 dump_packet (dev,skb,"recv");
#endif /* #ifdef DEBUG */

 skb->protocol = eth_type_trans (skb,dev);//网络层位何种协议

 netif_rx (skb);//将数据上传给网络层
 dev->last_rx = jiffies;//读取时间

 priv->stats.rx_packets++;
 priv->stats.rx_bytes += length;//更新状态
}

static int cirrus_send_start (struct sk_buff *skb,struct net_device *dev)//启动发送数据
{
 cirrus_t *priv = (cirrus_t *) dev->priv;
 u16 status;

 spin_lock_irq(&priv->lock);
 netif_stop_queue (dev);//停止队列

 cirrus_write (dev,PP_TxCMD,TxStart (After5));//Start transmission after 5 bytes are in the CS8900A
 cirrus_write (dev,PP_TxLength,skb->len);//提取套接字缓冲长度

 status = cirrus_read (dev,PP_BusST);//读取ISA总线状态

 if ((status & TxBidErr)) {//出错
  spin_unlock_irq(&priv->lock);
  printk (KERN_WARNING "%s: Invalid frame size %d!/n",dev->name,skb->len);
  priv->stats.tx_errors++;
  priv->stats.tx_aborted_errors++;
  priv->txlen = 0;
  return (1);
 }

 if (!(status & Rdy4TxNOW)) {//未准备好
  spin_unlock_irq(&priv->lock);
  printk (KERN_WARNING "%s: Transmit buffer not free!/n",dev->name);
  priv->stats.tx_errors++;
  priv->txlen = 0;
  /* FIXME: store skb and send it in interrupt handler */
  return (1);
 }

 cirrus_frame_write (dev,skb);//将数据从内存中复制到片内ram中
 spin_unlock_irq(&priv->lock);

#ifdef DEBUG
 dump_packet (dev,skb,"send");
#endif /* #ifdef DEBUG */

 dev->trans_start = jiffies;//记录发送时间

 dev_kfree_skb (skb);//释放套接字缓冲

 priv->txlen = skb->len;

 return (0);
}


static irqreturn_t cirrus_interrupt (int irq,void *id,struct pt_regs *regs)//中断处理函数
{
 struct net_device *dev = (struct net_device *) id;
 cirrus_t *priv;
 u16 status;

 int handled = 0;

 if (dev->priv == NULL) {
  printk (KERN_WARNING "%s: irq %d for unknown device./n",dev->name,irq);
  handled = 1;
  return 0;//IRQ_RETVAL(handled);
 }

 priv = (cirrus_t *) dev->priv;

 while ((status = cirrus_read (dev,PP_ISQ))) {//读中断寄存器
  handled = 1;
  switch (RegNum (status)) {
  case RxEvent:
   cirrus_receive (dev);//接受中断
   handled = 1;
   break;

  case TxEvent://发送中断
   priv->stats.collisions += ColCount (cirrus_read (dev,PP_TxCOL));//冲突加1
   if (!(RegContent (status) & TxOK)) {//发送失败
    priv->stats.tx_errors++;
    if ((RegContent (status) & Out_of_window)) priv->stats.tx_window_errors++;
    if ((RegContent (status) & Jabber)) priv->stats.tx_aborted_errors++;
    break;
   } else if (priv->txlen) {
    priv->stats.tx_packets++;
    priv->stats.tx_bytes += priv->txlen;
   }
   priv->txlen = 0;
   netif_wake_queue (dev);//开启队列
   handled = 1;
   break;

  case BufEvent:
   if ((RegContent (status) & RxMiss)) {
    u16 missed = MissCount (cirrus_read (dev,PP_RxMISS));
    priv->stats.rx_errors += missed;
    priv->stats.rx_missed_errors += missed;
   }
   if ((RegContent (status) & TxUnderrun)) {
    priv->stats.tx_errors++;
    priv->stats.tx_fifo_errors++;
   }
   // FIXME: if Rdy4Tx, transmit last sent packet (if any)
   priv->txlen = 0;
   netif_wake_queue (dev);
   handled = 1;
   break;

  case TxCOL:
   priv->stats.collisions += ColCount (cirrus_read (dev,PP_TxCOL));
   handled = 1;
   break;

  case RxMISS:
   status = MissCount (cirrus_read (dev,PP_RxMISS));
   priv->stats.rx_errors += status;
   priv->stats.rx_missed_errors += status;
   handled = 1;
   break;
  }
 }
  if(!handled) printk("Invalid cs8900 irq/n");
 return IRQ_HANDLED;//IRQ_RETVAL(handled);
}
  

static void cirrus_transmit_timeout (struct net_device *dev)//发送超时处理
{
 cirrus_t *priv = (cirrus_t *) dev->priv;
 priv->stats.tx_errors++;
 priv->stats.tx_heartbeat_errors++;
 priv->txlen = 0;
 netif_wake_queue (dev);
}

static int cirrus_start (struct net_device *dev)//打开
{
 int result;

 /* valid ethernet address? */
 if (!is_valid_ether_addr(dev->dev_addr)) {
  printk(KERN_ERR "%s: invalid ethernet MAC address/n",dev->name);
  return (-EINVAL);
 }

 /* install interrupt handler */
 printk("%s: requesting interrupt %i/n", __FUNCTION__, dev->irq);
 if ((result = request_irq (dev->irq,&cirrus_interrupt,0,dev->name,dev)) < 0) {
  printk (KERN_ERR "%s: could not register interrupt %d/n",dev->name,dev->irq);
  return (result);
 }
 else
  printk (KERN_ERR "%s: register interrupt %d/n",dev->name,dev->irq);
 
#if defined(CONFIG_ARCH_CSB226)
 set_irq_type(dev->irq, IRQT_RISING);//设置为上升中断模式
#endif

 /* enable the ethernet controller */
 cirrus_set (dev,PP_RxCFG,RxOKiE | BufferCRC | CRCerroriE | RuntiE | ExtradataiE);
 cirrus_set (dev,PP_RxCTL,RxOKA | IndividualA | BroadcastA);
 cirrus_set (dev,PP_TxCFG,TxOKiE | Out_of_windowiE | JabberiE);
 cirrus_set (dev,PP_BufCFG,Rdy4TxiE | RxMissiE | TxUnderruniE | TxColOvfiE | MissOvfloiE);
 cirrus_set (dev,PP_LineCTL,SerRxON | SerTxON);
 cirrus_set (dev,PP_BusCTL,EnableRQ);

#ifdef FULL_DUPLEX
 cirrus_set (dev,PP_TestCTL,FDX);
#endif /* #ifdef FULL_DUPLEX */

 /* start the queue */
 netif_start_queue (dev);

 MOD_INC_USE_COUNT;

 return (0);
}

static int cirrus_stop (struct net_device *dev)
{
 /* disable ethernet controller */
 cirrus_write (dev,PP_BusCTL,0);
 cirrus_write (dev,PP_TestCTL,0);
 cirrus_write (dev,PP_SelfCTL,0);
 cirrus_write (dev,PP_LineCTL,0);
 cirrus_write (dev,PP_BufCFG,0);
 cirrus_write (dev,PP_TxCFG,0);
 cirrus_write (dev,PP_RxCTL,0);
 cirrus_write (dev,PP_RxCFG,0);

 /* uninstall interrupt handler */
 free_irq (dev->irq,dev);

 /* stop the queue */
 netif_stop_queue (dev);

 MOD_DEC_USE_COUNT;

 return (0);
}

static int cirrus_set_mac_address (struct net_device *dev, void *p)//设置MAC码
{
 struct sockaddr *addr = (struct sockaddr *)p;
 int i;

 if (netif_running(dev))
  return -EBUSY;

 memcpy(dev->dev_addr, addr->sa_data, dev->addr_len);

 /* configure MAC address */
 for (i = 0; i < ETH_ALEN; i += 2)
  cirrus_write (dev,PP_IA + i,dev->dev_addr[i] | (dev->dev_addr[i + 1] << 8));

 return 0;
}

static struct net_device_stats *cirrus_get_stats (struct net_device *dev)//查看信息
{
 cirrus_t *priv = (cirrus_t *) dev->priv;
 return (&priv->stats);
}

static void cirrus_set_receive_mode (struct net_device *dev)//设置接受模式
{
 if ((dev->flags & IFF_PROMISC))
  cirrus_set (dev,PP_RxCTL,PromiscuousA);
 else
  cirrus_clear (dev,PP_RxCTL,PromiscuousA);

 if ((dev->flags & IFF_ALLMULTI) && dev->mc_list)
  cirrus_set (dev,PP_RxCTL,MulticastA);
 else
  cirrus_clear (dev,PP_RxCTL,MulticastA);
}

static int cirrus_eeprom_wait (struct net_device *dev)
{
 int i;

 for (i = 0; i < 200; i++) {
  if (!(cirrus_read (dev,PP_SelfST) & SIBUSY))
   return (0);
  udelay (1);
 }

 return (-1);
}

static int cirrus_eeprom_read (struct net_device *dev,u16 *value,u16 offset)
{
 if (cirrus_eeprom_wait (dev) < 0)
  return (-1);

 cirrus_write (dev,PP_EEPROMCommand,offset | EEReadRegister);

 if (cirrus_eeprom_wait (dev) < 0)
  return (-1);

 *value = cirrus_read (dev,PP_EEPROMData);

 return (0);
}

static int cirrus_eeprom (struct net_device *dev,cirrus_eeprom_t *eeprom)
{
 u16 offset,buf[16],*word;
 u8 checksum = 0,*byte;

 if (cirrus_eeprom_read (dev,buf,0) < 0) {
  read_timed_out:
  printk (KERN_DEBUG "%s: EEPROM read timed out/n",dev->name);
  return (-ETIMEDOUT);
 }

 if ((buf[0] >> 8) != 0xa1) {
  printk (KERN_DEBUG "%s: No EEPROM present/n",dev->name);
  return (-ENODEV);
 }

 if ((buf[0] & 0xff) < sizeof (buf)) {
  eeprom_too_small:
  printk (KERN_DEBUG "%s: EEPROM too small/n",dev->name);
  return (-ENODEV);
 }

 for (offset = 1; offset < (buf[0] & 0xff); offset++) {
  if (cirrus_eeprom_read (dev,buf + offset,offset) < 0)
   goto read_timed_out;

  if (buf[offset] == 0xffff)
   goto eeprom_too_small;
 }

 if (buf[1] != 0x2020) {
  printk (KERN_DEBUG "%s: Group Header #1 mismatch/n",dev->name);
  return (-EIO);
 }

 if (buf[5] != 0x502c) {
  printk (KERN_DEBUG "%s: Group Header #2 mismatch/n",dev->name);
  return (-EIO);
 }

 if (buf[12] != 0x2158) {
  printk (KERN_DEBUG "%s: Group Header #3 mismatch/n",dev->name);
  return (-EIO);
 }

 eeprom->io_base = buf[2];
 eeprom->irq = buf[3];
 eeprom->dma = buf[4];
 eeprom->mem_base = (buf[7] << 16) | buf[6];
 eeprom->rom_base = (buf[9] << 16) | buf[8];
 eeprom->rom_mask = (buf[11] << 16) | buf[10];

 word = (u16 *) eeprom->mac;
 for (offset = 0; offset < 3; offset++) word[offset] = buf[13 + offset];

 byte = (u8 *) buf;
 for (offset = 0; offset < sizeof (buf); offset++) checksum += byte[offset];

 if (cirrus_eeprom_read (dev,&offset,0x10) < 0)
  goto read_timed_out;

 if ((offset >> 8) != (u8) (0x100 - checksum)) {
  printk (KERN_DEBUG "%s: Checksum mismatch (expected 0x%.2x, got 0x%.2x instead/n",
    dev->name,
    (u8) (0x100 - checksum),
    offset >> 8);
  return (-EIO);
 }

 return (0);
}

/*
 * Architecture dependant code
 */

#ifdef CONFIG_SA1100_FRODO
static void frodo_reset (struct net_device *dev)
{
 int i;
 volatile u16 value;

 /* reset ethernet controller */
 FRODO_CPLD_ETHERNET |= FRODO_ETH_RESET;
 mdelay (50);
 FRODO_CPLD_ETHERNET &= ~FRODO_ETH_RESET;
 mdelay (50);

 /* we tied SBHE to CHIPSEL, so each memory access ensure the chip is in 16-bit mode */
 for (i = 0; i < 3; i++) value = cirrus_read (dev,0);

 /* FIXME: poll status bit */
}
#endif /* #ifdef CONFIG_SA1100_FRODO */

/*
 * Driver initialization routines
 */

void  __init reset_chip(struct net_device *dev)//复位芯片
{
    int reset_start_time;

    cirrus_write(dev, PP_SelfCTL, cirrus_read(dev, PP_SelfCTL) | RESET);

    /* wait 30 ms */
    current->state = TASK_INTERRUPTIBLE;
    schedule_timeout(30*HZ/1000);

    /* Wait until the chip is reset */
    reset_start_time = jiffies;
    while( (cirrus_read(dev, PP_SelfST) & INITD) == 0 &&
    jiffies - reset_start_time < 4)
      ;
}

static int io = 0;
static int irq = 0;

int __init cirrus_probe (struct net_device *dev)//探测函数
{
 static cirrus_t priv;
 int i,result;
 u16 value;
 cirrus_eeprom_t eeprom;

 printk ("Cirrus Logic CS8900A driver for Linux (V0.02)/n");

 memset (&priv,0,sizeof (cirrus_t));

 ether_setup (dev);//初始化公共成员
//
 dev->open               = cirrus_start;
 dev->stop               = cirrus_stop;
 dev->hard_start_xmit    = cirrus_send_start;//启动发送队列
 dev->get_stats          = cirrus_get_stats;
 dev->set_multicast_list = cirrus_set_receive_mode;
 dev->set_mac_address = cirrus_set_mac_address;
 dev->tx_timeout         = cirrus_transmit_timeout;//超时处理
 dev->watchdog_timeo     = HZ;//发送最大时间1ms

 /* hack!! */ // 00:05:5D:DD:81:18
 dev->dev_addr[0] = 0x00;
 dev->dev_addr[1] = 0x00;
 dev->dev_addr[2] = 0x02;
 dev->dev_addr[3] = 0x50;
 dev->dev_addr[4] = 0x10;
 dev->dev_addr[5] = 0x08;//mac码

 dev->if_port   = IF_PORT_10BASET;//选择rj45
 dev->priv      = (void *) &priv;

 SET_MODULE_OWNER (dev);

 dev->base_addr = CIRRUS_IOADDR;
 dev->irq = CIRRUS_IRQ;

 if (io > 0) dev->base_addr = io;
 if (irq > 0) dev->irq = irq;
  ///初始化私有数据结构
 
 if (!dev->base_addr) {//虚拟地址出错
  printk (KERN_ERR
    "%s: No default I/O base address defined. Use io=... or/n"
    "%s: define CIRRUS_DEFAULT_IO for your platform/n",
    dev->name,dev->name);
  return (-EINVAL);
 }

 if (!dev->irq) {
  printk (KERN_ERR
    "%s: No default IRQ number defined. Use irq=... or/n"
    "%s: define CIRRUS_DEFAULT_IRQ for your platform/n",
    dev->name,dev->name);
  return (-EINVAL);
 }

 if (!request_region (dev->base_addr,16,dev->name)) {//工作在IO模式时共有16个寄存器申请为IO端口
  printk (KERN_ERR "%s: can't get I/O port address 0x%lx/n",dev->name,dev->base_addr);
  return -EBUSY;
 }

#ifdef CONFIG_SA1100_FRODO
 frodo_reset (dev);
#endif /* #ifdef CONFIG_SA1100_FRODO */

 if (!cirrus_eeprom (dev,&eeprom))//使用片外EEPRAM保存MAC
  for (i = 0; i < 6; i++)
   dev->dev_addr[i] = eeprom.mac[i];

 //number for Crystal Semiconductor
 if ((value = cirrus_read (dev,PP_ProductID)) != EISA_REG_CODE) {
  printk (KERN_ERR "%s: incorrect signature 0x%.4x/n",dev->name,value);
  return (-ENXIO);
 }

 /* verify chip version */
 value = cirrus_read (dev,PP_ProductID + 2);
 if (VERSION (value) != CS8900A) {//是否为A版本芯片
  printk (KERN_ERR "%s: unknown chip version 0x%.8x/n",dev->name,VERSION (value));
  return (-ENXIO);
 }
 printk (KERN_INFO "%s: CS8900A rev %c detected/n",dev->name,'B' + REVISION (value) - REV_B);

 reset_chip(dev);//复位

 cirrus_write (dev,PP_IntNum,0);//使用0中断引脚

 for (i = 0; i < ETH_ALEN; i += 2)//将MAC码配置到Individual Address寄存器
  cirrus_write (dev,PP_IA + i,dev->dev_addr[i] | (dev->dev_addr[i + 1] << 8));

 return (0);
}

EXPORT_NO_SYMBOLS;

static struct net_device dev;//如此初始化?

static int __init cirrus_init (void)
{
 unsigned long extint1;

  extint1 = __raw_readl(S3C2410_EXTINT1);
  extint1 &= ~(7<<4);
  extint1 |= (4<<4);
  __raw_writel(extint1, S3C2410_EXTINT1);//设置EIN9为上升沿中断

 memset (&dev,0,sizeof (struct net_device));//网络结构体初始化
 dev.init = cirrus_probe;//硬件初始化函数
 return (register_netdev (&dev));//注册网络设备
}

static void __exit cirrus_cleanup (void)
{
 release_region (dev.base_addr,16);
 unregister_netdev (&dev);
}

MODULE_AUTHOR ("Abraham van der Merwe <abraham@2d3d.co.za>");
MODULE_DESCRIPTION ("Cirrus Logic CS8900A driver for Linux (V0.02)");
MODULE_LICENSE ("GPL");
MODULE_PARM_DESC (io,"I/O Base Address");
MODULE_PARM (io,"i");
MODULE_PARM_DESC (irq,"IRQ Number");
MODULE_PARM (irq,"i");

module_init (cirrus_init);
module_exit (cirrus_cleanup);

 

验证步骤:
1.将开发板和PC用交叉网线连接,将两者的IP地址设为同一局域网段后互ping对方,都可以正常ping通;
2.TCP/IP程序的service--client服务测试,将service上传到开发板运行再运行client均可以发送和接收。
应用测试程序如下:
#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <time.h>
#define SERVER_PORT 12345 // define the defualt connect port id
#define LENGTH_OF_LISTEN_QUEUE 10 //length of listen queue in server
#define BUFFER_SIZE 255
#define WELCOME_MESSAGE "welcome to connect the server. "
int main(int argc, char **argv)
{
     printf("The beginning of main function./n");
       int servfd,clifd;
       struct sockaddr_in servaddr,cliaddr;
      if ((servfd = socket(AF_INET,SOCK_STREAM,0)) < 0)//建立套接字----AF_INET为IPv4协议 SOCK_STREAM:字节流套接字socket(它使用 TCP 协议)
       {
              printf("create socket error!/n");
              exit(1);
       }
       bzero(&servaddr,sizeof(servaddr));
       servaddr.sin_family = AF_INET;
       servaddr.sin_port = htons(SERVER_PORT);//将16bit端口号换成网络字符顺序--端口号用s,ip地址用l
       servaddr.sin_addr.s_addr = htonl(INADDR_ANY);//ip地址可以以后配置
      //将32bit IP地址换成网络字符顺序 #define INADDR_ANY (u_int32_t)0x00000000
       if (bind(servfd,(struct sockaddr*)&servaddr,sizeof(servaddr))<0)//将本地IP地址绑定端口号
       {
              printf("bind to port %d failure!/n",SERVER_PORT);
              exit(1);
       }
       if (listen(servfd,LENGTH_OF_LISTEN_QUEUE) < 0)//服务器等待客户端的连接请求
       {
              printf("call listen failure!/n");
              exit(1);
       }
 while(1){
  printf("The beginning of the circle./n");
              char buf[BUFFER_SIZE];
              long timestamp;
              socklen_t length = sizeof(cliaddr);
     printf("before accept function ./n");
              clifd = accept(servfd,(struct sockaddr*)&cliaddr,&length);//accept用于等待客户端的数据包到来(是阻塞函数)
     printf("after accept function./n");
              if (clifd < 0){
                     printf("error comes when call accept!/n");
   return 1;
                }
              strcpy(buf,WELCOME_MESSAGE);
              //inet_ntop(INET_ADDRSTRLEN,cliaddr.sin_addr,buf,BUFFER_SIZE);
              printf("from client,IP:%s,Port:%d/n",inet_ntoa(cliaddr.sin_addr),ntohs(cliaddr.sin_port));//打印客户端IP地址和端口号
              timestamp = time(NULL);
              strcat(buf,"timestamp in server:");
              strcat(buf,ctime(&timestamp));//字符连接之后为"welcome to connect the server.timestamp in server: time"
              send(clifd,buf,BUFFER_SIZE,0);//发送客户端
              close(clifd);          
 }
       close(servfd);
       return 0;
}//服务端程序

 

#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <stdlib.h>
#define SERVER_PORT 12345 // define the defualt connect port id
#define CLIENT_PORT 12345 // define the defualt client port as a random port
#define BUFFER_SIZE 255
#define REUQEST_MESSAGE "welcome to connect the server./n"
int main(int argc, char **argv)
{    
       int servfd,clifd,length = 0;
       struct sockaddr_in servaddr,cliaddr;
       socklen_t socklen = sizeof(servaddr);
       char buf[BUFFER_SIZE];
while(1){
       if ((clifd = socket(AF_INET,SOCK_STREAM,0)) < 0)
       {
              printf("create socket error!/n");
              exit(1);
       }
       srand(time(NULL));//获得当前的时间作为随机数的种子
       bzero(&cliaddr,sizeof(cliaddr));
       cliaddr.sin_family = AF_INET;
       cliaddr.sin_port = htons(CLIENT_PORT);
       cliaddr.sin_addr.s_addr = htonl(INADDR_ANY);//客户端IP地址可以配置
       servaddr.sin_family = AF_INET;
       inet_aton("192.168.10.100",&servaddr.sin_addr);//指定要连接的服务端IP地址
       servaddr.sin_port = htons(SERVER_PORT);
       if (connect(clifd,(struct sockaddr*)&servaddr, socklen) < 0) {//用于client端与服务器端建立连接
              printf("can't connect to %s!/n",argv[1]);
              exit(1);
       }   
      length = recv(clifd,buf,BUFFER_SIZE,0);//接收服务端数据
       if (length < 0)
       {
              printf("error comes when recieve data from server %s!",argv[1]);
              exit(1);
       }
       printf("from server %s :/n/t%s ",argv[1],buf);
       close(clifd);
}
       return 0;
}//客户端程序

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值