6. Network Communications

 

 

Topics:

• Networks; topology, OSI model, hardware and design issues

• Network types; Ethernet

• Internet; addressing

 

Objectives:

• Networks; topology, OSI model, hardware and design issues

• Network types; Ethernet

• Internet; addressing

 

 

The simplest form of communication is a direct connection between two computers. A network will simultaneously connect a large number of computers on a network.

 

Data communications have evolved from the 1800’s when telegraph machines were used to transmit simple messages using Morse code. This process was automated with teletype machines that allowed a user to type a message at one terminal, and the results would be printed on a remote terminal. Meanwhile, the telephone system began to emerge as a large network for interconnecting users. In the late 1950s Bell Telephone introduced data communication networks, and Texaco began to use remote monitoring and control to automate a polymerization plant. By the 1960s data communications and the phone system were being used together. In the late 1960s and 1970s modern data communications techniques were developed. This included the early version of the Internet, called ARPAnet. Before the 1980s the most common computer configuration was a centralized mainframe computer with remote data terminals, connected with serial data line. In the 1980s the personal computer began to displace the central computer. As a result, high speed networks are now displacing the dedicated serial connections. Serial communications and networks are both very important in modern control applications.

 

 

6.1 Networks

 

A computer with a single network interface can communicate with many other computers. This economy and flexibility has made networks the interface of choice, eclipsing point-to-point methods such as RS-232. Typical advantages of networks include resource sharing and ease of communication. But, networks do require more knowledge and understanding.

 

Small networks are often called Local Area Networks (LANs). These may connect a few hundred computers within a distance of hundreds of meters. These networks are inexpensive, often costing $100 or less per network node. Data can be transmitted at rates of millions of bits per second. Many controls system are using networks to communicate with other controllers and computers. Typical applications include;

• taking quality readings with a PLC and sending the data to a database computer.

• distributing recipes or special orders to batch processing equipment.

• remote monitoring of equipment.

 

Larger Wide Area Networks (WANs) are used for communicating over long distances between LANs. These are not common in controls applications, but might be needed for a very large scale process. An example might be an oil pipeline control system that is spread over thousands of miles.

 

 

6.1.1 Topology

 

The structure of a network is called the topology. Figure 22.12 shows the basic network topologies. The ’Bus’ and ’Ring’ topologies both share the same network wire. In the ’Star’ configuration each computer has a single wire that connects it to a central hub.

 

Figure 22.12 - Network Topologies

 

In the ’Ring’ and ’Bus’ topologies the network control is distributed between all of the computers on the network. The wiring only uses a single loop or run of wire. But, because there is only one wire, the network will slow down significantly as traffic increases. This also requires more sophisticated network interfaces that can determine when a computer is allowed to transmit messages. It is also possible for a problem on the network wires to halt the entire network.

 

The ’Star’ topology requires more wire overall to connect each computer to an intelligent hub. But, the network interfaces in the computer become simpler, and the network becomes more reliable. Another term commonly used is that it is deterministic, this means that performance can be predicted. This can be important in critical applications.

 

For a factory environment the bus topology is popular. The large number of wires required for a star configuration can be expensive and confusing. The loop of wire required for a ring topology is also difficult to connect, and it can lead to ground loop problems. Figure 12.13 shows a tree topology that is constructed out of smaller bus networks. Repeaters are used to boost the signal strength and allow the network to be larger.

 

Figure 22.13 - The Tree Topology

 

 

6.1.2 OSI Network Model

 

The Open System Interconnection (OSI) model in Figure 22.14 was developed as a tool to describe the various hardware and software parts found in a network system. It is most useful for educational purposes, and explaining the things that should happen for a successful network application. The model contains seven layers, with the hardware at the bottom, and the software at the top. The darkened arrow shows that a message originating in an application program in computer #1 must travel through all of the layers in both computers to arrive at the application in computer #2. This could be part of the process of reading email.

 

Figure 22.14 - The OSI Network Model

 

The ’Physical’ layer describes items such as voltage levels and timing for the transmission of single bits. The ’Data Link’ layer deals with sending a small amount of data, such as a byte, and error correction. Together, these two layers would describe the serial byte shown in Figure 22.3. The ’Network’ layer determines how to move the message through the network. If this were for an internet connection this layer would be responsible for adding the correct network address. The ’Transport’ layer will divide small amounts of data into smaller packets, or recombine them into one larger piece. This layer also checks for data integrity, often with a checksum. The ’Session’ layer will deal with issues that go beyond a single block of data. In particular it will deal with resuming transmission if it is interrupted or corrupted. The ’Session’ layer will often make long term connections to the remote machine. The ’Presentation’ layer acts as an application interface so that syntax, formats and codes are consistent between the two networked machines. For example this might convert ’\’ to ’/’ in HTML files. This layer also provides subroutines that the user may call to access network functions, and perform functions such as encryption and compression. The ’Application’ layer is where the user program resides. On a computer this might be a web browser, or a ladder logic program on a PLC.

 

Most products can be described with only a couple of layers. Some networking products may omit layers in the model. Consider the networks shown in Figure 22.15.

 

 

6.1.3 Networking Hardware

 

The following is a description of most of the hardware that will be needed in the design of networks.

 

• Computer (or network enabled equipment)

• Network Interface Hardware - The network interface may already be built into the computer/PLC/sensor/etc. These may cost $15 to over $1000.

• The Media - The physical network connection between network nodes.

10baseT (twisted pair) is the most popular. It is a pair of twisted copper wires terminated with an RJ-45 connector.

10base2 (thin wire) is thin shielded coaxial cable with BNC connectors

10baseF (fiber optic) is costly, but signal transmission and noise properties are very good.

• Repeaters (Physical Layer) - These accept signals and retransmit them so that longer networks can be built.

• Hub/Concentrator - A central connection point that network wires will be connected to. It will pass network packets to local computers, or to remote networks if they are available.

• Router (Network Layer) - Will isolate different networks, but redirect traffic to other LANs.

• Bridges (Data link layer) - These are intelligent devices that can convert data on one type of network, to data on another type of network. These can also be used to isolate two networks.

• Gateway (Application Layer) - A Gateway is a full computer that will direct traffic to different networks, and possibly screen packets. These are often used to create firewalls for security.

 

Figure 22.15 shows the basic OSI model equivalents for some of the networking hardware described before.

 

Figure 22.15 - Network Devices and the OSI Model

 

Figure 22.15X - The OSI Network Model with a Router

 

 

6.1.4 Control Network Issues

 

A wide variety of networks are commercially available, and each has particular strengths and weaknesses. The differences arise from their basic designs. One simple issue is the use of the network to deliver power to the nodes. Some control networks will also supply enough power to drive some sensors and simple devices. This can eliminate separate power supplies, but it can reduce the data transmission rates on the network. The use of network taps or tees to connect to the network cable is also important. Some taps or tees are simple ’passive’ electrical connections, but others involve sophisticated ’active’ tees that are more costly, but allow longer networks.

 

The transmission type determines the communication speed and noise immunity. The simplest transmission method is baseband, where voltages are switched off and on to signal bit states. This method is subject to noise, and must operate at lower speeds. RS-232 is an example of baseband transmission. Carrierband transmission uses FSK (Frequency Shift Keying) that will switch a signal between two frequencies to indicate a true or false bit. This technique is very similar to FM (Frequency Modulation) radio where the frequency of the audio wave is transmitted by changing the frequency of a carrier frequency about 100MHz. This method allows higher transmission speeds, with reduced noise effects. Broadband networks transmit data over more than one channel by using multiple carrier frequencies on the same wire. This is similar to sending many cable television channels over the same wire. These networks can achieve very large transmission speeds, and can also be used to guarantee real time network access.

 

The bus network topology only uses a single transmission wire for all nodes. If all of the nodes decide to send messages simultaneously, the messages would be corrupted (a collision occurs). There are a variety of methods for dealing with network collisions, and arbitration.

CSMA/CD (Collision Sense Multiple Access/Collision Detection) - if two nodes start talking and detect a collision then they will stop, wait a random time, and then start again.

CSMA/BA (Collision Sense Multiple Access/Bitwise Arbitration) - if two nodes start talking at the same time the will stop and use their node addresses to determine which one goes first.

Master-Slave - one device one the network is the master and is the only one that may start communication. slave devices will only respond to requests from the master.

Token Passing - A token, or permission to talk, is passed sequentially around a network so that only one station may talk at a time.

 

The token passing method is deterministic, but it may require that a node with an urgent message wait to receive the token. The master-slave method will put a single machine in charge of sending and receiving. This can be restrictive if multiple controllers are to exist on the same network. The CSMA/CD and CSMA/BA methods will both allow nodes to talk when needed. But, as the number of collisions increase the network performance degrades quickly.

 

 

6.1.5 Ethernet

 

Ethernet has become the predominate networking format. Version I was released in 1980 by a consortium of companies. In the 1980s various versions of ethernet frames were released. These include Version II and Novell Networking (IEEE 802.3). Most modern ethernet cards will support different types of frames.

 

The ethernet frame is shown in Figure 20.21. The first six bytes are the destination address for the message. If all of the bits in the bytes are set then any computer that receives the message will read it. The first three bytes of the address are specific to the card manufacturer, and the remaining bytes specify the remote address. The address is common for all versions of ethernet. The source address specifies the message sender. The first three bytes are specific to the card manufacturer. The remaining bytes include the source address. This is also identical in all versions of ethernet. The ’ethernet type’ identifies the frame as a Version II ethernet packet if the value is greater than 05DChex. The other ethernet types use these to bytes to indicate the datalength. The ’data’ can be between 46 to 1500 bytes in length. The frame concludes with a ’checksum’ that will be used to verify that the data has been transmitted correctly. When the end of the transmission is detected, the last four bytes are then used to verify that the frame was received correctly.

 

Figure 22.21 - Ethernet Version II Frame

 

• TCP vs UDP

 

 

6.1.6 SLIP and PPP

 

Ethernet connections are not always practical for computers at a distance, or when networking hardware is not available. A common alternative is to use a serial connection, such as a telephone modem. Network data packets are passed using a protocol such as Serial Line Internet Protocol (SLIP) and Point to Point Protocol (PPP).

 

At present the alternatives for data transfer are listed below. This is a short list, but it can be expected to grow quickly over time.

Phone lines with modem (dial up) - this runs at speeds up to 56Kbaud, with a peak data rate of about 3KB/sec. These are used for network connection that lasts from a few minutes to hours. This is very widespread and universally supported, but expect this 40 year old technology to be phased out over the next decade.

Direct serial connection - this can be done with a direct connection between serial ports on two computers using SLIP or PPP. The peak rates can reach over 6KB/sec. This method can also be done using a low speed radio modem.

Direct parallel connection - this is done by connecting the parallel ports on two computers together and using Parallel Line Interface Protocol (PLIP). Data rates approaching 1MB/sec are possible.

ISDN - Integrated Services Digital Network (ISDN) uses dedicated phone lines that require a special interface card. Data rates reach 56Kbaud, but lines can be added in parallel to increase the speed. These tend to be high cost and are less popular.

DSL - Digital Subscriber Line (DSL) - This technology uses an existing residential phone line, but at frequencies above the audio range. The network connection is always active, but telephone usage can be permitted at any time. These have a faster data transfer rate than dial up connections, but still have a higher cost.

Cable - These broadband networks provide a permanent network connection that uses existing cable television networks. Special networking hardware is required. These networks are notable because the download speeds is higher than the download speed.

Satellite - These connections are available at a high cost and are suitable for remote locations where other communications access is not possible.

Fiber - Not available yet, but should be soon in high population areas. Expect very high speed access.

 

 

6.2 Internet

 

The Internet is a collection of networking technologies, such as Ethernet, SLIP, PPP and others that allows computers to communicate and exchange information. The concept of the Internet began with ARPANET which was funded as a Department of Defense project in 197x. In 198x the Internet was developed, and began to replace the ARPANET. By the late 1980s the Internet was widespread between most universities, colleges, major companies and government agencies around the world. Finally, the Internet hit widespread public usage by the mid 1990s. Today it is the accepted defacto standard network in the world.

 

Originally the Internet was used to exchange email and files. It was common to anonymously log into a remote computer, with FTP, and upload and download files. In the early 1990s a number of new applications were developed to make interaction with remote computers easier. For example ’archie’ made it easy to search for files by names. ’wais’ and ’gopher’ were early predecessors to ’mosiac’ which then lead to ’netscape’. At that time (about 1993) the face of the internet started to change, thanks to the World Wide Web (WWW). Non-professional users of the internet started to arrive through the America On-Line (AOL) service. This also coincided with the first major case of ’spam’, where a legal firm mass mailed advertisements for immigration services. Finally, by the mid 1990s microsoft stopped referring to the Internet as a ’fad’. Today, most people and companies vie for an Internet presence.

 

This section will outline some of the core concepts that are important when designing applications that use the Internet.

 

 

6.2.1 Computer Addresses

 

Most users are familiar with text computer names, such as ’www.gvsu.edu’. But, these names are only for convenience, and the same computer can have multiple names. Consider the example below. The machine ’claymore.engineer.gvsu.edu’ can also be called with ’www.eod.gvsu.edu’. In actuality, each computer on the network has a unique four number address. Both of the names below refer to the same computer with the numerical address ’148.61.104.215’. The digits of the address can range from 0 to 255.

 

 

When a text computer name is supplied it is converted to a numerical address before network access occurs. Consider the case where a computer name is typed into a web browser. The web browser will then call another computer called a Domain Name Server (DNS). The DNS computer has a database of local and remote computers names and numbers. It will convert the computer name to a number, and then return it to the web browser. The web browser then uses the computer number to connect to the named computer.

 

The number has four parts. The first two digits ‘148.61’ indicate to all of the internet that the computer is at ‘gvsu.edu’ (we actually pay a yearly fee to register this). The third number indicates what LAN the computer is located on (Basically each sub-network has its own number). Finally the last digit is specific to a machine. This addressing method makes it easy to direct network traffic.

 

There are different classes on networks. The largest is a class A, in which the entire network begins with the same number such as ’148.’, allowing up the last three numbers to be used for local network addresses. The next smaller network is class B, in which the first two numbers are designated, for example ’148.61.’. A class C network specifies the first three digits, such as ’148’61.104.’, and can have up to 256 addresses. The ’netmask’ indicates how many computers can be on a network. A common netmask is ’255.255.255.0’ which indicates the local network can have up to 256 computers. A netmask of ’255.255.255.254’ would indicate that there are only two computers on the network.

 

When a packet of information is sent it passes through many computers between the sender and receiver. Each of the computers is configured to know where the next computer is upstream and downstream. The ’gateway’ is the computer on a local area network that passes a packet out to the Internet. For example, if my computer address is 192.168.1.20, the gateway is probably 192.168.1.254. Any packets travelling to/from the Internet will travel through the gateway computer.

 

The current standard of four number network addresses is called IPV4. This addressing scheme is ultimately limited, and so the address space is being expanded from four numbers to six in the newer IPV6 standard. This standard also introduces some enhancements for security and other applications.

 

 

6.2.2 Computer Ports

 

On the network information is sent in packets. These are addressed to a computer using the IPV4 address, but they also include a port number between 0 and 65535. The port number indicates what service they are trying to access. In general the first 1000 are allocated to well known and agreed upon services, such as email and web serving. Other port numbers in the low thousands are for less common network services, and numbers in the high thousands are used by user programs. An abbreviated list of common network ports is given below. On any computer the may or may not be active.

23? 24? - telnet

xxx - ftp

25 - smtp

80 - http

110 - pop3

118 - sqlserv

143 - imap

515 - printer

520 - router

1433 - mssql

26000 - quake

 

 

6.3 Networking in Linux

 

Configuration files are under /etc

Recompile kernel in some cases, such as a firewall. or new hardware

Loadable modules

DHCP versus static IP

 

 

Most modern versions of Linux simplify hardware detection and setup. The steps below can help perform the basic operations, or find problems.

A. Installing a normal ethernet network connection:

1. During the installation process you will be asked for network parameters.

2. Enter a unique name for the machine and the network name.

3. (for DHCP) All that should be required is a setting for DHCP.

3. (for a static IP) You will need to enter the static IP number for the machine, as well as a netmask and gateway. If you are connecting to another network you can get these from a network administrator. If you are connecting your own network (not on the Internet) you can simply pick values like those below. Note that you need some sort of network router with an IP address of 192.168.1.254 for this to work.

IP address: 192.168.1.20

netmask: 255.255.255.0

Gateway: 192.168.1.254

nameserver: none

B. Troubleshooting an ethernet connection to the Internet,

1. Check to see if the network card is recognized with ’more /proc/modules’ The card should be in the list. If not the kernel module must be installed.

2. Check to see if the network is setup with ifconfig. You should see ’eth0’ or something similar. If it is not setup, the network parameters must be checked.

3. Check to see if the network is connected properly with ping to the local gateway, or another local machine - use the IP number, not the name. For example, ’ping 148.61.104.254’. If this fails the gateway or broadcast addresses are probably incorrect.

4. Check the connection to the outside with a ping such as ’ping 148.61.1.10’. If this is not allowed there is probably a problem with the outside connection

5. Verify that the nameserver is working alright with a ping to a named machine such as, ’ping www.linux.org’.

6. If all of these things work the network connection should be alright.

C. Installing a dialup connection

1. During the installation make sure that the location of your modem is correctly identified. Note: Winmodems are very popular because of their low cost, but there are very few Linux drivers. But... you are advised to spend the money for a non-Winmodem anyway, they are more reliable and they don’t use your computers resources.

2.

D. Troubleshooting a dialup connection

1. Use a terminal program to dial the Internet service provider’s number manually. If you don’t get a response there is a problem with the modem installation.

2. After connected try providing your login ID and password and see if you get in. Expect to see garbage after this. If login is refused you need to check the user ID and password again.

3. Check ...

E. Setting up a firewall (this requires some work)

1. To set up a firewall the kernel must be recompiled to include network options such as multicasting, and firewall services.

[KERNEL OPTIONS]

2. Shut down the computer and add a second network card in the machine and reboot.

3. Check to see if the card is recognized with ’more /proc/modules’. Both ethernet cards should be listed. If not you will need to edit the network startup files. These are normally in ’/etc/...’ or for slackware ’/etc/rc.d’. An example file follows. Reboot and check for both network cards again.

[NETWORK CONFIG FILES]

4. Use ’ipchains’ to add services to pass, and modify the ’hosts.allow’ and ’hosts.deny’ files to control access.

[ipchains file declarations]

[hosts.allow file]

[hosts.deny file]

 

 

6.3.1 Network Programming in Linux

 

The following listings show network usage in Linux. The general method of network connection is different for servers and clients.

 

For servers.....

 

 

For clients....

 

 

Listing X.1 - network_io.cpp

 

 

#include "network_io.h"

 

#include <sys/poll.h>

#include <sys/ioctl.h>

#include <linux/tcp.h>

 

#include <stdio.h>

#include <string.h>

#include <unistd.h>

#include <fcntl.h>

 

 

network_io::network_io(){

type = _READ;

level = 0;

}

 

 

network_io::~network_io(){

if(type == _READ){

if(level > 1){

if(level > 2){

end_read_connection();

}

deinit_read();

}

} else if (type == _WRITE){

 

}

}

 

 

int network_io::set_remote_host(char *_host_name, int host_socket){

static int error;

static int nm_a,

nm_b,

nm_c,

nm_d;

struct hostent *hp;

unsigned char address[4];

 

error = NO_ERROR;

strcpy(host_name, _host_name);

host_socket_number = host_socket;

 

// Set up server descriptor, get host reference and error trap

write_connection.sin_family = AF_INET;

if((host_name[0] > ’9’) ||(host_name[0]<’0’)){

hp = gethostbyname(host_name);

} else {

sscanf(host_name, "%d.%d.%d.%d",

&nm_a, &nm_b, &nm_c, &nm_d);

address[0] = (unsigned char)(nm_a);

address[1] = (unsigned char)(nm_b);

address[2] = (unsigned char)(nm_c);

address[3] = (unsigned char)(nm_d);

hp = gethostbyaddr((char *)address, 4, AF_INET);

}

 

if(hp != 0){

/* complete descriptor set up. */

bcopy((char *)hp->h_addr,

(char *)&(write_connection.sin_addr),

hp->h_length);

} else {

error_log(MINOR, "ERROR: unknown network host");

error = ERROR;

}

 

return error;

}

 

 

int network_io::set_local_host(int socket_num){

static int error;

 

error = NO_ERROR;

socket_number = socket_num;

 

return error;

}

 

 

 

 

int network_io::writer(char *string){

static int error;

 

error = NO_ERROR;

 

// Open a new socket for the write, and check for errors.

error = init_write();

if(error == NO_ERROR) error = open_write_connection();

if(error == NO_ERROR) error = write_to_connection(string);

if(error == NO_ERROR) error = end_write_connection();

if(deinit_write() == ERROR) error = ERROR;

 

return(error);

}

 

 

 

int network_io::reader(char *buf, int length){

static int error; // Error return variable

 

error = NO_ERROR;

 

// Wait for a socket connection request, then get its reference.

buf[0] = 0;

if(wait_read_connection() == NO_ERROR){

if(read_from_connection(buf, length) == ERROR){

}

// Close socket connection to remote write client.

end_read_connection();

}

 

return(error);

}

 

 

int network_io::init_write(){

static int error;

struct hostent *gethostbyname();

 

error = NO_ERROR;

/* Open a new socket for the write, and check for errors. */

if((rw_socket = socket(AF_INET, SOCK_STREAM, 0)) >= 0){

write_connection.sin_port = htons(host_socket_number);

} else {

error_log(MINOR, "ERROR: opening stream socket");

error = ERROR;

}

 

return error;

}

 

 

int network_io::open_write_connection(){

static int error;

 

error = NO_ERROR;

if(connect(rw_socket, (struct sockaddr *) &(write_connection), sizeof(write_connection)) < 0){

error = ERROR;

error_log(MINOR, "ERROR: Connecting stream Socket");

}

 

return error;

}

 

 

int network_io::write_to_connection(char *text){

static int error;

 

error = NO_ERROR;

if(write(rw_socket, text, strlen(text) /* +1 */) < 0){

error_log(MINOR, "ERROR: writing on stream socket");

error = ERROR;

}

 

return error;

}

 

 

int network_io::write_stuff_done(){

int error;

 

error = NO_ERROR;

return error;

}

 

 

int network_io::check_connection(){

int error;

int count;

struct pollfd ufds;

 

error = NO_ERROR;

ufds.fd = rw_socket;

ufds.events = POLLOUT | POLLIN | POLLPRI | POLLERR | POLLHUP | POLLNVAL;

count = poll(&ufds, 1, 0);

if((ufds.revents & 16) != 0) error = ERROR;

 

return error;

}

 

 

int network_io::end_write_connection(){

static int error;

 

error = NO_ERROR;

 

return error;

}

 

 

int network_io::deinit_write(){

static int error;

 

error = NO_ERROR;

close(rw_socket);

rw_socket = ANY;

 

return error;

}

 

 

int network_io::init_read(){

static int error; // low level socket number

unsigned length; // temporary work variable

static struct sockaddr_in server; // read socket descriptor

static struct hostent *hp;

char text[100];

 

// Open internet socket, and check for error.

error = ERROR;

gethostname(text, 100); /* who are we? */

hp = gethostbyname(text);

if((hp != NULL) && (read_socket = socket(AF_INET, SOCK_STREAM, 0)) >= 0){

// Set up server descriptor for binding name.

memset(&server, 0, sizeof(struct sockaddr_in));

server.sin_family = hp->h_addrtype;

server.sin_port = htons(socket_number);

// Bind the socket, and check for error.

level = 1;

int flag = 1;

setsockopt(read_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&flag, sizeof(int));

if(bind(read_socket, (struct sockaddr *)&server, sizeof(struct sockaddr_in)) >= 0){

 

// Check for valid socket binding

length = sizeof(server);

if(getsockname(read_socket, (struct sockaddr *)&server, &length) >= 0){

error = NO_ERROR;

// Set up variables for success

// Zero because anything higher would allow

// messages to arrive out of sequence.

listen(read_socket, 0);

} else {

error_log(MINOR, "ERROR: getting socket name");

}

} else {

error_log(MINOR, "ERROR: binding stream socket");

}

} else {

error_log(MINOR, "ERROR: opening stream socket");

}

 

return(error);

}

 

 

int network_io::read_stuff_waiting(){

int error,

count;

struct pollfd ufds;

 

error = ERROR;

ufds.fd = read_socket;

ufds.events = POLLIN | POLLPRI | POLLOUT;

count = poll(&ufds, 1, 0);

if((ufds.revents & 1) > 0){

error = NO_ERROR;

}

 

return error;

}

 

 

int network_io::wait_read_connection(){

static int error;

unsigned size;

static struct sockaddr addr;

 

error = NO_ERROR;

size = sizeof(struct sockaddr);

fcntl(read_socket, F_SETFL, O_NONBLOCK);

rw_socket = accept(read_socket, &addr, &size);

 

level = 2;

if(rw_socket < 0){

error = ERROR;

// error_log("ERROR: warning:accept");

}

 

return error;

}

 

 

int network_io::read_from_connection(char *buf, int length){

int error;

int len;

 

error = NO_ERROR;

// Empty input buffer

buf[0] = 0;

// Read string into buffer from socket

fcntl(rw_socket, F_SETFL, O_NONBLOCK);

len = read(rw_socket, buf, length);

if(len < 0){

// error_log("ERROR: reading stream message");

// error = ERROR;

if(errno != 11){

printf("errno=%d ", errno);

}

} else {

buf[len] = 0;

}

 

return error;

}

 

 

int network_io::end_read_connection(){

int error;

int a;

 

error = NO_ERROR;

a = close(rw_socket);

level = 1;

 

return error;

}

 

 

int network_io::deinit_read(){

int error;

int a;

 

error = NO_ERROR;

a = close(read_socket);

level = 0;

 

return error;

}

 

 

char *network_io::get_address(){

static char work[MAXIMUM_HOST_NAME_LENGTH];

struct sockaddr_in address;

int i,

addr[4];

long int_address;

#ifndef SGI

// Sun Version

get_myaddress(&address);

int_address = address.sin_addr.s_addr;

#else

// SGI Version

int_address = gethostid();

#endif

// SUN & SGI version

for(i = 0; i < 4; i++){

addr[i]=int_address & 0xFF;

int_address >>= 8;

}

#ifdef OTHER_UNIX

sprintf(work, "%d.%d.%d.%d",

(int)addr[3], (int)addr[2], (int)addr[1], (int)addr[0]);

#else

// This is for linux

sprintf(work, "%d.%d.%d.%d",

(int)addr[0], (int)addr[1], (int)addr[2], (int)addr[3]);

#endif

return work;

}

 

 

char *network_io::get_remote_client(){

staticchar work[100];

struct sockaddr address;

socklen_t len;

 

len = sizeof(address);

if(getpeername(rw_socket, &address, &len) == 0){

sprintf(work, "%u.%u.%u.%u", address.sa_data[2], address.sa_data[3], address.sa_data[4], address.sa_data[5]);

// printf("Got address [%s]\n", work);

//strcpy(work, address);

} else {

strcpy(work, "unknown network address");

}

 

return work;

}

 

 

 

 

Listing X.2 - network_io.h

 

#ifndef _NETWORK_IO

#define _NETWORK_IO

 

 

#include <errno.h>

#include <linux/socket.h> // sys/socket.h may be needed here

#include <sys/types.h>

#include <netdb.h>

#include <rpc/rpc.h>

#include <unistd.h>

 

 

#define ANY 0 // Indicates no socket number prechosen

 

 

#define MAXIMUM_HOST_NAME_LENGTH 100

class network_io{

public:

int socket_number;

int rw_socket;

// int read_connection;

char host_name[MAXIMUM_HOST_NAME_LENGTH];

int host_socket_number;

int read_socket;

struct sockaddr_in write_connection;

// char incoming_string[MAXIMUM_STRING_SIZE];

 

int type;

int level;

#define _READ 200

#define _WRITE 201

network_io();

~network_io();

int set_remote_host(char*, int);

int set_local_host(int);

int reader(char*, int);

int writer(char*);

int init_write();

int open_write_connection();

int write_to_connection(char*);

// int write_to_read_connection(char*);

int end_write_connection();

int deinit_write();

int init_read();

int wait_read_connection();

int read_from_connection(char*, int);

// int read_from_write_connection(char*, int);

int end_read_connection();

int deinit_read();

int read_stuff_waiting();

int write_stuff_done();

int check_connection();

char* get_remote_client();

 

char *get_address();

};

 

#endif

 

 

 

Listing X.3 - network.cpp

 

 

#include "../network_io/network_io.h"

#include <time.h>

 

 

network_io *network;

int mode;

char *params;

char received_temp[200];

int connect_flag;

time_t now_time;

time_t last_time;

int timeout;

 

 

int main(){

timeout = 5; // the default timeout

 

return 1;

}

 

 

int deinit(){

int error;

 

error = NO_ERROR;

if(network != NULL) delete network;

 

return error;

}

 

 

int process_command();

int check_network();

 

 

int step(){

int error;

 

error = NO_ERROR;

error = check_network();

if(error == NO_ERROR) error = process_command();

 

return error;

}

 

 

 

int check_network(){

int error;

 

error = NO_ERROR;

 

if(*state == WAITINGFORCONNECTION){

if(connect_flag == TRUE){

if(mode == LISTENER){

if(network->wait_read_connection() == NO_ERROR){

char text[200];

*state = CONNECTIONESTABLISHED;

*received_flag = FALSE;

*send_flag = FALSE;

sprintf(text, "Got a connection from %s", network->get_remote_client());

error_log(WARNING, text);

time(&last_time);

}

} else if(mode == TALKER){

if(network->open_write_connection() == NO_ERROR){

*state = CONNECTIONESTABLISHED;

*received_flag = FALSE;

*send_flag = FALSE;

time(&last_time);

}

}

}

} else if(*state == CONNECTIONESTABLISHED){

if(*send_flag == TRUE){

network->write_to_connection(send_buf);

// printf("Sending String [%s]\n", send_buf);

send_buf[0] = 0;

*send_flag = FALSE;

// time(&last_time); // You can keep the connection alive by writing

// but this doesn’t guarantee that the remote client is still there

}

if(*received_flag == FALSE){

if(network->read_from_connection(received_temp, 199) != ERROR){

if(strlen(received_temp) > 0){

strcpy(received, received_temp);

*received_flag = TRUE;

time(&last_time);

// printf("Got String [%s]\n", received);

}

}

}

time(&now_time);

if((network->check_connection() == ERROR) || ((mode == LISTENER) && (difftime(now_time, last_time) > timeout))){

if(mode == LISTENER){

network->end_read_connection();

} else if(mode == TALKER){

network->end_write_connection();

}

*state = WAITINGFORCONNECTION;

connect_flag = FALSE;

}

}

 

return error;

}

 

 

 

int process_command(){

int error;

int i, len;

int port;

 

error = NO_ERROR;

if(*change_lock == TRUE){

if(*command == INITIALIZE){

if(*state == NOTINITIALIZED){

if(mode == LISTENER){

port = atoi(params);

if(port > 0){

network = new network_io();

network->set_local_host(port);

network->init_read();

//now ready to listen

*state = WAITINGFORCONNECTION;

connect_flag = FALSE;

} else {

error_log(MINOR, "Parameter did not hold a valid port");

*error_flag = ERROR;

}

} else if(mode == TALKER){

len = strlen(params);

for(i = 0; i < len; i++){

if(params[i] == ’:’){

params[i] = 0;

port = atoi(&(params[i+1]));

break;

}

}

if((i < len) && (port > 0)){

network = new network_io();

network->set_remote_host(params, port);

network->init_write();

*state = WAITINGFORCONNECTION;

connect_flag = FALSE;

} else {

error_log(MINOR, "Address string was not properly formed");

*error_flag = ERROR;

}

} else {

error_log(MINOR, "ERROR: Mode not defined yet");

*error_flag = ERROR;

}

} else {

error_log(MINOR, "Network talker initialize command in wrong state");

*error_flag = ERROR;

}

} else if(*command == CONNECT){

if(*state == WAITINGFORCONNECTION){

connect_flag = TRUE;

}

} else if(*command == DISCONNECT){

if(*state == CONNECTIONESTABLISHED){

if(mode == TALKER){

network->end_write_connection();

} else if (mode == LISTENER){

network->end_read_connection();

}

*state = WAITINGFORCONNECTION;

connect_flag = FALSE;

} else {

error_log(MINOR, "Cannot disconnect network unless connected");

*error_flag = ERROR;

}

} else if(*command == UNINITIALIZE){

if(*state == WAITINGFORCONNECTION){

if(mode == TALKER){

network->deinit_write();

} else if (mode == LISTENER){

network->deinit_read();

}

delete network;

network = NULL;

*state = NOTINITIALIZED;

} else {

error_log(MINOR, "Cannot uninitialize network unless waitingforconnection");

*error_flag = ERROR;

}

} else if(*command == SET){

if(*operand1 == MODE){

if(*state == NOTINITIALIZED){

mode = *operand2;

} else {

error_log(MINOR, "Can’t set network mode after initialization");

*error_flag = ERROR;

}

} else if(*operand1 == PARAM){

if(*state == NOTINITIALIZED){

if(params != NULL) delete params;

params = new char[strlen(operand3)+1];

strcpy(params, operand3);

} else {

error_log(MINOR, "Can’t set network parameters, in wrong state");

*error_flag = ERROR;

}

} else if(*operand1 == TIMEOUT){

timeout = *operand2;

} else {

error_log(MINOR, "Network SET type not recognized");

*change_lock = FALSE;

*error_flag = ERROR;

}

} else {

error_log(MINOR, "Network command not recognized");

*error_flag = ERROR;

}

}

*change_lock = FALSE;

 

return error;

}

 

 

 

To use the network program as a server the basic flow of control is outlined below,

char temp_in[200]; // an input string

char temp_out[200]; // an output string

 

// set up the network connection

network_io test = new network_io(); // create a new instance of network

test->set_local_host(1000); // set the program to listen on port 1000

point1: test->init_read(); // start waiting for a client to connect

point2: val = test->wait_read_connection(); // check for a connection

if(val == ERROR) goto point2;

val = test->check_connection();

if(val == ERROR){

test->end_read_connection();

goto point1;

}

// now connected, interact with client

point3: val = test->read_from_connection(temp_in, 199); // get an input string

if(val == NO_ERROR){

// do anything needed for the received string

}

 

// do anything for writing strings here

if(there is a string to send){

test->write_to_connection(temp_out);

}

goto point3;

 

 

A makefile for the program follows.

 

all: network

CC=c++

CFLAGS=

network: network.cpp

$(CC) $(CFLAGS) network.cpp -o network network_io.o

network_io.o: network_io.cpp network_io.h

$(CC) $(CFLAGS) -c network_io.cpp

 

 

6.4 Summary

 

• Networks come in a variety of topologies, but buses are most common on factory floors.

• The OSI model can help when describing network related hardware and software.

• Networks can be connected with a variety of routers, bridges, gateways, etc.

• Ethernet is common, and can be used for high speed communication.

• The internet can be use to monitor and control shop floor activities.

 

 

6.5 Practice Problems

 

1. Explain why networks are important in manufacturing controls.

 

(ans. These networks allow us to pass data between devices so that individually controlled systems can be integrated into a more complex manufacturing facility. An example might be a serial connection to a PLC so that SPC data can be collected as product is made, or recipes downloaded as they are needed.)

 

2. Is the OSI model able to describe all networked systems?

 

(ans. The OSI model is just a model, so it can be used to describe parts of systems, and what their functions are. When used to describe actual networking hardware and software, the parts may only apply to one or two layers. Some parts may implement all of the layers in the model.)

 

3. What are the different methods for resolving collisions on a bus network?

 

(ans. When more than one client tries to start talking simultaneously on a bus network they interfere, this is called a collision. When this occurs they both stop, and will wait a period of time before starting again. If they both wait different amounts of time the next one to start talking will get priority, and the other will have to wait. With CSMA/CD the clients wait a random amount of time. With CSMA/BA the clients wait based upon their network address, so their priority is related to their network address. Other networking methods prevent collisions by limiting communications. Master-slave networks require that client do not less talk, unless they are responding to a request from a master machine. Token passing only permits the holder of the token to talk.)

 

 

 

 

6.6 Laboratory - Networking

 

Purpose: To expose you to the architecture and components of a modern computer network.

 

Objectives: To be able to set up a switch and computers to communicate over an Intranet network.

 

Background:

 

Computers can be connected via a network. At a minimum this requires a network card in at least two computers and a connecting cable between them. These computers can then pass packets of information back and forth for basic communication. This type of connection is commonly used by people playing games such as Quake at home. A more mature network, like that found in a factory, must be more sophistocated.

 

The most fundamental concept in a network is the data packets and the protocol for exchanging them. The current Internet protocol is called IPV4 (this will be replaced by IPV6 in the near future). In this protocol each client on a network has a 4 byte (0-255) address, normally shown in the form ‘aaa.bbb.ccc.ddd’. In our case the university is a ‘class B’, so it owns all addresses that start with ‘148.61.ccc.ddd’. Most engineering students use a ‘class C’ network with the addresses ‘148.61.104.ddd’. In theory there are up to 256 clients on the engineering network. In practice some of these addresses are used for network housekeeping. For example the following addresses are used,

148.61.104.1 - this is the router/switch to other networks

148.61.104.254 - this is the gateway to other networks

 

If a network address is not used, it can be used by a normal network device, such as a computer or printer. There are two ways to assign these statically or dynamically. In a static connection the address can only be used by one machine. In a dynamic connection the addresses are assigned and release semi-randomly to network clients as the connect and disconnect from the network. Static IP addresses are primarily designed for computers that are always on, and are acting as servers on the network. Dynamic IP addresses are primarily used for computers that are only clients on the network. Some examples of static IP addresses on the network are:

148.61.104.215 - claymore.engineer.gvsu.edu

148.61.104.226 - excalibur.engineer.gvsu.edu

148.61.104.??? - falcon.engineer.gvsu.edu

etc..

 

Most computers on the network are named, such as ‘gvsu.edu’. When a user enters this name into the computer, it must be converted to a network number. This is done by a ‘domain name server’ (DNS). There are two DNS servers at GVSU (148.61.1.10 and 148.61.1.15). These servers keep all of the names for computers at GVSU, and also provide links to computers at other sites so that their names and numbers can also be searched.

 

Although the engineering student network is ‘148.61.104.ddd’, it is actually a collection of smaller networks (sub-nets). The smaller networks are connected together with network devices called switches/hubs/routers. These are basically small computers with multiple network connections (often 24). Each computer is connected to the hub. The hub then looks at each network packet coming from a computer. If it is going to another computer connected to the same hub, it will be sent there directly. Otherwise it is sent ‘up-stream’ to a router that will send it to another sub-net if it is available, or up upstream again. In our lab we will use a Linksys 10/100 Managed 24-Port GigaSwitch (EG24M).

 

The Switch in the lab is used to connect computers together, and connect to a network gateway. ....

 

The server for the lab is.....

Network Components:

Lab Server - Claymore

Dell Poweredge 1300 Server

Intel Pro/100 network card (internet side)

3Com 590 network card (infranet side)

Adaptec SCSI card 2940U2W (2 cards) for SCSI hard disks

Tape drive -

Uninterruptable Power Supply - APC Smart-UPS 120V OL103

 

Firewall....

 

 

6.6.1 Prelab

 

1. Find and read the user manual for the Linksys 10/100 Managed 24-Port GigaSwitch (EG24M). http://www.linksys.com

 

2. At a windows computer look at the settings for the network. On windows 9x this is done with ’winipcfg’, on windows nt use the network settings. Look at the options available, copy out the settings to hand in. After that use the following instructions, and describe what each is doing.

nslookup claymore.engineer.gvsu.edu

ping claymore.engineer.gvsu.edu

ping 148.61.104.215

tracert claymore.engineer.gvsu.edu

tracert gvsu.edu

tracert www.umich.edu

route

netstat

netstat -a

 

3. Open a Dos window and type ‘telnet river.it.gvsu.edu 25’. this will connect you to the main student computer. But instead of the normal main door, you are talking to a program that delivers mail. Type the following to send an email message.

 

4. Go to the web site ’www.arin.net’ and look up some machine names there under the ’whois’ link. Determine who owns the student network, i.e., 148.61.104.

 

5. While looking at a home page in Netscape select ‘View - Page Source’. You will see a window that includes the actual HTML file - This file was interpreted by Netscape to make the page you saw previously. Look through the file to see if you can find any text that was on the original page.

 

6. In Netscape ask for the location ‘ftp://sunsite.unc.edu’ This will connect you via ftp the same way as with the windows and the dos software.

 

7. In netscape type in ‘mailto:YOUR_NAME@river.it.gvsu.edu’ (Note: If the mail server information and a user account is not setup an error window will appear.). After you are done try ‘news:gvsu’.

 

8. Using Netscape try to access the IP number of the machine beside you. You will get a message that says the connection was refused. This is because the machine is a client. You have already been using servers to get web pages.

 

9. When we ask for a computer by name, your computer must find the number. It does this using a DNS (Domain Name Server). On campus we have two ‘148.61.1.10’ and ‘148.61.1.15’. In a Linux machine type in the following commands and determine what they have done. You can get access to a linux machine from a windows machine by typing ’telnet claymore.engineer.gvsu.edu’.

 

 

6.6.2 Laboratory

 

1. Connect to the Linksys switch using telnet 192.168.1.2, user ’guest’, password ______. In this case the switch can be accessed and used from anywhere on the network. Normally this access is disabled, and the switch is controlled using a direct serial connection.

 

2. Configure your computer to be a static client on the lab TCP/IP network with the address assigned by the instructor.

3. Download the example programs from the web, compile them and run them. You will see the two programs send messages back and forth.

4. Write a simple time server. When a user connects it will send the current time, and then disconnect one second later. It will then wait for a new connection. Use a socket number above 2000 to avoid potential conflicts with other system resources.

5. Write two programs, a chat server and client. At both ends the user can type a message, and it will be displayed on the remote computer.