Вы находитесь на странице: 1из 32

hanging the MAC address in W2K and XP (this page stolen from http://www.klcconsulting.net/change_mac_w2k.

htm because I wanted a copy in my notes here so I wouldn't lose it)


Method 1: This is depending on the type of Network Interface Card (NIC) you have. If you have a card that doesnt support Clone MAC address, then you have to go to second method.

a. Go to Start->Settings->Control Panel and double click on Network and Dial-up Connections. b. Right click on the NIC you want to change the MAC address and click on properties. c. Under General tab, click on the Configure button d. Click on Advanced tab e. Under Property section, you should see an item called Network Address or "Locally Administered Address", click on it. f. On the right side, under Value, type in the New MAC address you want to assign to your NIC. Usually this value is entered without the - between the MAC address numbers. g. Goto command prompt and type in ipconfig /all or net config rdr to verify the changes. If the changes are not materialized, then use the second method. h. If successful, reboot your systems.

Method 2: This method requires some knowledge on the Windows Registry. If you are not familiar with Windows Registry, just use the SMAC tool to change the MAC addresses, or consult with a technical person before you attempt on the following steps. Also, make sure you have a good backup of your registry. a. Goto command prompt and type ipconfig /all, and I. Record the Description for the NIC you want to change. II. Record the Physical Address for the NIC you want to change. Physical Address is the MAC Address

figure 1. b. Goto command prompt and type net config rdr, and you should see something like

figure 2. c. Remember the number between the long number (GUID) inside the { }. For example, in the above net config rdr output, for MAC address 00C095ECB793, you should remember {1C9324AD-ADB7-4920-B02DAB281838637A}. You can copy and paste it to the Notepad, thats probably the easiest way. (See figure 2.) d. Go to Start -> Run, type regedt32 to start registry editor. Do not use Regedit. e. Do a BACKUP of your registry in case you screw up the following steps. To do this I. Click on HKEY_LOCAL_MACHINE on Local Machine sub-window II. Click on the root key HKEY_LOCAL_MACHINE. III. Click on the drop-down menu Registry -> Save Subtree As and save the backup registry in to a file. Keep this file in a safe place.

f. Go to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4D36 E972-E325-11CE-BFC1-08002BE10318}. Double click on it to expand the tree. The subkeys are 4-digit numbers, which represent particular network adapters. You should see it starts with 0000, then 0001, 0002, 0003 and so on. (See figure 3.)

Figure 3. g. Go through each subkey that starts with 0000. Click on 0000, check DriverDesc keyword on the right to see if that's the NIC you want to change the MAC address. The DriveDesc should match the Description you recorded from step (a.-I.). If you are not 100% sure about the DriverDesc, then you can verify by checking if the NetCfgInstanceID keyword value matches the GUID from step (c). If there is no match, then move on to 0001, 0002, 0003, and so on, until you find the one you want. Usually 0000 contains the first NIC you installed on the computer. In this demonstration, 0000 is the NIC I selected. (See figure 3.) h. Once you selected the subkey (i.e. 0000), check if there is a keyword "NetworkAddress" exist in the right side of the window. (See figure 3.) I. If "NetworkAddress" keyword does not exist, then create this new keyword: i. Click on the drop down menu Edit -> Add Value.

ii. In the Add Value window, enter the following value then click OK. (See figure 4.) Value Name: = NetworkAddress Data Type: = REG_SZ

Figure 4. iii. String Editor window will pop up at this time (see figure 5.) iv. Enter the new MAC address you want to modify. Then click OK. (There should not be any "-" in this address. Your entry should only consist of 12 digits as seen in the figure 5.) II. If "NetworkAddress" keyword exists, make sure it shows the keyword type is REG_SZ, and it should show as NetworkAddress:REG_SZ: . This keyword might not have a value at this time. i. Double click on the keyword NetworkAddress and the String Editor window will pop up. (See Figure 5.) ii. Enter the new MAC address you want to modify. Then click OK. (There should not be any "-" in this address. Your entry should only consist of 12 digits as seen in the figure 5.)

Figure 5. j. There are 2 ways to make the new MAC address active. Method I does not require a system reboot: I. Goto Start->Setting->Control Panel, and double click on "Network Neighborhood". WARNING: Make sure you understand that you WILL lose the network connection after completing step "ii." below, and

if you have a DHCP client, you will get a new IP address after completing step "iii." i. Select the Network Adaptor you just changed the MAC address. ii. Right click on the selected Network Adaptor and click "Disable." Verify the status column for this adaptor changes to "Disabled" iii. Right click on the selected Network Adaptor and click "Enable." Verify the status column for this adaptor changes to "Enabled" iv. If for any reason it cannot be disabled or re-enabled, you have to reboot your system to make the changes effective. II. Reboot your Windows system. k. Once completing step j (if rebooting the system, wait until the reboot is completed), go to command prompt, type ipconfig /all to confirm the new MAC address. 00-14-85-7C-F3-08 80-90-91-00-19-91 Restore The TRUE Hardware burned-in MAC Address: a. Remove the entry you added: I. II. If you followed Method 1, then go back to the advanced properties window and remove the entry you add. If you followed Method 2, then remove the "NetworkAddress" keyword you added in the registry.

b. Use step (j) above to activate the change you make. c. Once rebooted, go to command prompt, type ipconfig /all to confirm the original MAC address.

If MAC Address changes does not work: If for whatever reason the MAC address cannot be changed using method 2, make sure you restore the registry setting by following the "Restore The TRUE Hardware burned-in MAC Address" instruction above. If necessary, restore the registry you just backed-up to get your system back to the original state. You can do this by clicking on the drop-down menu Registry>Restore, and restore your backup registry file.

or use SMAC

-----------------------------Another good article on changing MAC addresses http://www.tech-faq.com/change-mac-address.shtml which leads to another program that appears geared more torwards XP and can change MAC addresses http://students.washington.edu/natetrue/macshift/ but if for some reason that link evaporates you can find a local copy here

MAC address (Media Access Control address) is a quasi-unique identifier consists of a six byte number that attached to most network adapter card or network interface card (NIC). As such, all network cards, whether its of Ethernet NIC, Gigabit Ethernet NIC or wireless 802.11a/b/g/n WiFi or HiperLAN adapter, should have different MAC addresses, which also known as Ethernet Hardware Address (EHA) or adapter address. In operating system, MAC address is often represented in 12-digit hexadecimal number. For example, 1A-2B-3C-4D-5E-6F. In practical usage, layer 2 MAC address is converted from layer 3 protocol addresses such as Internet Protocol (IP address) by ARP (Address Resolution Protocol), which then allowed each host to be uniquely identified and frames to be marked for specific hosts on broadcast networks, such as Ethernet. After translated (or when a host on LAN sends its MAC address to another machine which does n ot configured not to accept unrequested ARP replies on the network for preemptive caching), MAC address is cached on source PC ARP table for later use. Content of ARP table on each computer can be viewed by typing arp -a in Windows or arp in Linux. MAC address thus forms the basis of most of the layer 2 networking upon which higher OSI Layer protocols are built to produce complex, functioning networks. There are many reasons or possibilities that an user may want to change the MAC address or a network adapter, which also known as MAC spoofing. For example, to bypass the MAC address filtering on firewall or router. The trick can be used to get pass the network access restriction by emulating a new unrestricted MAC address, or to gain access connection by spoof an authorized MAC address after sniffing the legitimate MAC address out of the air in MAC filtering Wi-Fi network. Beside, hackers or enthusiasts also spoofing another hosts MAC address as their own in order to receive traffic packets not meant for them, although ARP poisoning technique is more commonly used. However, changing MAC address can still keep the real information from been detected and logged by various services such as IDS, firewall, DHCP server, wireless access points and etc, and is essential protect users privacy. MAC spoofing also potentially trigger a Denial of Service (DoS) attack by causing routing problem with duplicating MAC address exists in the network, especially those similar with gateway and AP routers BSSID (Basic Service Set Identifier.) Whatever the reason, its pretty easy to change the MAC address or perform MAC spoofing on most of todays hardware, listed below. Actually, the original MAC address is burnt and imprinted to the network card, and cannot be changed. However, operating system can spoof as if there is different MAC address for the network interface card using tricks below. Change the MAC address in Windows

1. Go to Start -> Control Panel. Double click on Network Connections (inside Network and Internet Connections category in Windows XP). The, right click on the active network connection with network adapter that you want to change the MAC address (normally Local Area Network or Wireless Network Connection) and click on Properties. Above steps work in Windows XP, Windows 2000 and Windows Server 2003. For Windows Vista, access to NICs properties is from Control Panel -> Network and Internet -> Network and Sharing Center > Manage Network Connections. Alternatively, if you already know which network adapter thats responsible for your network or Internet connection, go to Device Manager and open the properties dialog by double click on the NIC itself. 2. In the General tab, click on the Configure button. 3. Click on Advanced tab. 4. In the Property section, select and highlight Network Address or Locally Administered Address. 5. To the right, Not Present radio button is by default selected as value. Change the value by clicking on radio button for Value:, and then type in a new MAC address to assign to the NIC.

The MAC address consists of 6 pairs of numbers (0 9) and characters (A F) combination. For example, 88-17-E8-90-E2-0A. When entering the new MAC value, omit the dash (-), for example 8817E890E20A. 6. Click OK when done. 7. To verify the change of MAC address, go to command prompt, then type in one of the following commands: ipconfig /all net config rdr 8. Reboot the computer if successful to make the change effective. Note: To restore or reset back to original default MAC address, simply set back the opti on to Not Present. Change the MAC Address of NIC in Windows via Registry 1. Open a command prompt. 2. Type the following command and hit Enter. ipconfig /all 3. Record down the Description and the Physical Address (is MAC address) of the active network connection (discard those with Media Disconnected state).

For example, in figure above, Description is Intel(R) Wireless WiFi Link 4965AGN and MAC address is in the format of 00-XX-XX-XX-XX-XX. 4. In the command prompt also, type the following command and hit Enter. net config rdr 5. Record down the GUID for the MAC address for the active connections NIC which MAC address to be changed. The GUID is contained within the { and } brackets right in front of the MAC address as shown in figure below.

6. Type regedt32 or regedit in Start -> Run box or in Start Search for Windows Vista. Note: for Windows NT 4.0 and Windows 2000, regedt32 must be used. 7. Navigate to the following registry key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC108002BE10318} 8. Expand the {4D36E972-E325-11CE-BFC1-08002BE10318} tree, and there will be more sub-keys in the form of 0000, 0001, 0002 and so on. 9. Go through each sub-key starting from 0000, look for subkey that has DriverDesc value data that matches NIC description copied from step above, that want its MAC address to be changed. In most cases, it will be similar to the network adapter card name. To verify that the subkey found is indeed a correct one, check the value of the NetCfgInstanceId, which should have the same value with the NICs GUID taken from step above. 10. Once a sub-key is matched to the network interface card that MAC address want to be spoofed, select and highlight the subkey. Right click on the sub-key (for example, 0000), then select New ->String Value. Name the new value name as NetworkAddress. Note: If NetworkAddress REG_SZ registry key is already existed in the right pane, skip this step. 11. The double click on NetworkAddress and enter a new MAC address as its value data.

Note that the 12-digit MAC address in hexadecimal format, and should be entered without any dash (-). For example, 1A2B3C4D5E6F. 12. Reboot the system to make the new MAC address effective. Alternatively, if you dont want to restart the system, try to disable and then re-enable the network adapter in Device Manager. 13. To verify the change of MAC address, go to command prompt, then type in one of the following commands: ipconfig /all net config rdr Note: To restore or reset back to true original hardware burned-in MAC address, remove the NetworkAddress registry key that is been added. Alternative: Third party tools and utilities to change the MAC address in Windows operating system are plenty, for example: SMAC (direct download link to smac20_setup.ex, supports Windows Vista, XP, 2003, 2000), Macshift (direct download link to macshift.zip, for Windows XP), BMAC (almost identical SMAC MAC changer clone by moorer-software.com), Mac MakeUp (direct download link tomacmakeup.zip, for Windows 2000/XP/2003/Vista), MadMACs (MAC Address Spoofing And Host Name Randomizing App For Windows, directly download MadMACs.zip), EtherChange (direct download link to etherchange.exe), and Technitium MAC Address Changer (for Windows 2000 / XP / Server 2003 / Vista / Server 2008).

Server code

import java.net.*;

1
import java.io.*;

public class Server {

3 4 5 6 7 8 9
byte [] bytearray = new byte [(int)transferFile.length()]; ServerSocket serverSocket = new ServerSocket(15123); Socket socket = serverSocket.accept(); System.out.println("Accepted connection : " + socket); File transferFile = new File ("Document.doc"); public static void main (String [] args ) throws IOException {

10 11 12 13 14 15 16 17 18
}

FileInputStream fin = new FileInputStream(transferFile); BufferedInputStream bin = new BufferedInputStream(fin); bin.read(bytearray,0,bytearray.length); OutputStream os = socket.getOutputStream(); System.out.println("Sending Files..."); os.write(bytearray,0,bytearray.length); os.flush(); socket.close(); System.out.println("File transfer complete");

19 20 21 22

Client code

1 2 import java.net.*; 3 import java.io.*; 4 public class Client { 5 6 7 8


int currentTot = 0; public static void main (String [] args ) throws IOException { int filesize=1022386; int bytesRead;

9 10 11 12 13 14 15 16 17 18

Socket socket = new Socket("127.0.0.1",15123); byte [] bytearray = new byte [filesize];

InputStream is = socket.getInputStream(); FileOutputStream fos = new FileOutputStream("copy.doc"); BufferedOutputStream bos = new BufferedOutputStream(fos); bytesRead = is.read(bytearray,0,bytearray.length); currentTot = bytesRead;

do { bytesRead = is.read(bytearray, currentTot, (bytearray.length-currentTot));

19 20 21 22 23 24 25 26}

if(bytesRead >= 0) currentTot += bytesRead; } while(bytesRead > -1);

bos.write(bytearray, 0 , currentTot); bos.flush(); bos.close() socket.close();

First we will discuss the coding for server side, we are going to import all the classes which are needed by the Server class: Listing1 : Importing classes

1array0
Here java.net is for importing the ServerSocket and the Socket class. These classes are used for defining the server connection port number and also are used for accepting connections from the client. Now we define the class along with the main function: Listing2: Class and main method

1public class Server { 2 3 4 5


ServerSocket serverSocket = new ServerSocket(15123); public static void main (String [] args ) throws IOException {

The name of class is Server, we defined a variable serverSocket of ServerSocket type inside the main method. Actually here serverSocket waits for incoming client connection on port 15123 which is specified as argument above (chosen randomly) and accepts the connection when it gets one. Now we will define the main logic in the program: Listing3 : Main Logic

1 2 3 4 5 6 7 8 9

Socket socket = serverSocket.accept(); System.out.println("Accepted connection : " + socket); File transferFile = new File ("Document.doc"); byte [] bytearray = new byte [(int)transferFile.length()];

FileInputStream fin = new FileInputStream(transferFile); BufferedInputStream bin = new BufferedInputStream(fin); bin.read(bytearray,0,bytearray.length); OutputStream os = socket.getOutputStream(); System.out.println("Sending Files..."); os.write(bytearray,0,bytearray.length);

10 11 12 13 14
} }

os.flush(); socket.close(); System.out.println("File transfer complete");

15 16
Now we explain this: serverSocket.accept() waits for any client connection and once any clients tries on to connect on server it accepts the connection and then store it in socket object of the Socket class. We define the file to be transferred as Document.doc in a file variable named transferFile. We define a bytearray which will contain temporary data, define the fin and bin object to read from the transferFile and the data read would be filled in the bytearray object, bin.read method is used to read the file and the data read is stored in the bytearray. We define a OutStream which here provides a channel to communicate with client side. We write the data read from the bytearray onto the output stream. We close the objects using the close method.

Client.java
Now we will come to coding at Client side: First we import all the classes. Listing4: Import classes

1array0
Here java.net is for importing the Socket class. These classes are used for defining the server ip address and the port number of the server. Now we will define the class and the main method: Listing5: Defining classes and methods

1public class Client { 2 3 4 5


public static void main (String [] args ) throws IOException { int filesize=2022386; int bytesRead;

int currentTot = 0;

We defined a class named Client, Main method and a variable filesize which can be thought of like a buffer size. bytesRead contain the current statistics of the bytes read from the input channel ie inputstream, currentTot contains the total number of bytes read. Now we will add the processing part: Listing6: Main Logic

1 2 3 4
FileOutputStream fos = new FileOutputStream("copy.doc"); Socket socket = new Socket("127.0.0.1",15123); byte [] bytearray = new byte [filesize];

InputStream is = socket.getInputStream();

5 6 7 8 9 10 11 12 13 14 15 16

BufferedOutputStream bos = new BufferedOutputStream(fos); bytesRead = is.read(bytearray,0,bytearray.length); currentTot = bytesRead;

do { bytesRead = is.read(bytearray, currentTot, (bytearray.length-currentTot)); if(bytesRead >= 0) currentTot += bytesRead; } while(bytesRead > -1);

bos.write(bytearray, 0 , currentTot); bos.flush(); bos.close();

17 18 19} 20
}

socket.close();

We defined a Socket object which try to connect on ip 127.0.0.1(local ip in my case, change it when you try on lan with ip of your friends computer) on port number 15123. We define a variable byteArray which will act just like a buffer to hold

temporary data, InputStream object called in which will help us to collect all information passed to input channel of client ie files or even the messages which are transferred to client. We define the FileOutputStream object which point to the file which will be filled with data copied from the server file. The BufferedOutputStream helps us to write data to the output file via a byte array. We read the data from the inputstream using the read method of the object. The data read from the input channel is stored in the byte array. We initially set currentTot to number of bytes read. Now we implement a do-while loop. It read again from the input stream and now if the bytesRead is >=0 then we update out currentTot object. When the byteRead is -1 i.e. there is no data left on the inputstream then the do-while loop exits. After that we write the finally read bytes on the file and then close the stream. Full Source code:

import java.io.*; import java.net.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Client extends JFrame { private JTextField enterField; private JTextArea displayArea; private ObjectOutputStream output; private ObjectInputStream input; private String message = ""; private String chatServer; private Socket client;

public Client( String host ) { super( "Client" ); chatServer = host; Container container = getContentPane(); enterField = new JTextField(); enterField.setEditable( false ); enterField.addActionListener ( new ActionListener() { public void actionPerformed( ActionEvent event ){ sendData( event.getActionCommand() );

enterField.setText( "" ); } } ); container.add( enterField, BorderLayout.NORTH );

// create displayArea
displayArea = new JTextArea(); container.add( new JScrollPane( displayArea ), BorderLayout.CENTER ); setSize( 300, 150 ); setVisible( true ); }

// connect to server and process messages from server


private void runClient() { try { connectToServer(); getStreams(); processConnection(); } catch ( EOFException eofException ) { System.err.println( "Client terminated connection" ); }

catch ( IOException ioException ) { ioException.printStackTrace(); } finally { closeConnection(); } }

// connect to server

private void connectToServer() throws IOException { displayMessage( "Attempting connection\n" ); client = new Socket( InetAddress.getByName( chatServer ), 12345 ); displayMessage( "Connected to: " +client.getInetAddress().getHostName() ); }

// get streams to send and receive data


private void getStreams() throws IOException { output = new ObjectOutputStream( client.getOutputStream() ); input = new ObjectInputStream( client.getInputStream() ); }

// process connection with server


private void processConnection() throws IOException { setTextFieldEditable( true ); do {

// read message and display it


try { message = ( String ) input.readObject(); displayMessage( "\n" + message ); } catch ( ClassNotFoundException classNotFoundException ) { displayMessage( "\nUnknown object type received" ); } } while ( !message.equals( "SERVER>>> TERMINATE" ) ); }

// close streams and socket


private void closeConnection() { displayMessage( "\nClosing connection" ); setTextFieldEditable( false );

try { output.close(); input.close(); client.close(); } catch( IOException ioException ) { ioException.printStackTrace(); } }

// send message to server


private void sendData( String message ) { try { output.writeObject( "CLIENT>>> " + message ); output.flush(); displayMessage( "\nCLIENT>>> " + message ); } catch ( IOException ioException ) { displayArea.append( "\nError writing object" ); } }

// utility method called from other threads to manipulate // displayArea in the event-dispatch thread
private void displayMessage( final String messageToDisplay ) { SwingUtilities.invokeLater ( new Runnable() { public void run() { displayArea.append( messageToDisplay ); displayArea.setCaretPosition( displayArea.getText().length() ); } } ); }

private void setTextFieldEditable( final boolean editable ) { SwingUtilities.invokeLater ( new Runnable() { public void run() { enterField.setEditable( editable ); } } ); } public static void main( String args[] ) { Client application; if ( args.length == 0 ) application = new Client( "127.0.0.1" ); else application = new Client( args[ 0 ] ); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); application.runClient(); } } ...

import java.io.*; import java.net.*; import java.awt.*; import java.awt.event.*; import javax.swing.*;

public class Server extends JFrame { private JTextField enterField; private JTextArea displayArea; private ObjectOutputStream output; private ObjectInputStream input;

private ServerSocket server; private Socket connection; private int counter = 1;

// set up GUI
public Server(){ super( "Server" );
Container container = getContentPane();

// create enterField and register listener


enterField = new JTextField(); enterField.setEditable(false); enterField.addActionListener(

new ActionListener()
{

// send message to client


public void actionPerformed(ActionEvent event)
{ sendData( event.getActionCommand() ); enterField.setText( "" ); } ); container.add( enterField, BorderLayout.NORTH ); displayArea = new JTextArea(); container.add( new JScrollPane( displayArea ), BorderLayout.CENTER );

setSize( 300, 150 ); setVisible( true );

// set up and run server


public void runServer()
{

try{

server = new ServerSocket( 12345, 100 );

while ( true ) {

try {
waitForConnection(); getStreams(); processConnection(); }

// process EOFException when client closes connection


catch ( EOFException eofException ){
System.err.println( "Server terminated connection" ); }

finally {
closeConnection(); ++counter; }

// process problems with I/O


catch ( IOException ioException )

{ ioException.printStackTrace(); }

// wait for connection to arrive, then display connection information


private void waitForConnection() throws IOException
{ displayMessage( "Waiting for connection\n" ); connection = server.accept(); // allow server to accept connection displayMessage( "Connection " + counter + " received from: " + connection.getInetAddress().getHostName() ); }

// get streams to send and receive data


private void getStreams() throws IOException
{ output = new ObjectOutputStream( connection.getOutputStream() );

input = new ObjectInputStream( connection.getInputStream() );

// process connection with client


private void processConnection() throws IOException
{ String message = "Connection successful"; sendData( message );

setTextFieldEditable( true );

do {

try
{ message = ( String ) input.readObject(); displayMessage( "\n" + message ); }

catch ( ClassNotFoundException classNotFoundException )


{ displayMessage( "\nUnknown object type received" ); }

} while ( !message.equals( "CLIENT>>> TERMINATE" ) );

// close streams and socket


private void closeConnection()
{ displayMessage( "\nTerminating connection\n" ); setTextFieldEditable( false ); // disable enterField

try
{ output.close(); input.close(); connection.close(); }

catch( IOException ioException )


{ ioException.printStackTrace(); } }

// send message to client


private void sendData( String message )
{

try
{ output.writeObject( "SERVER>>> " + message );

displayMessage( "\nSERVER>>> " + message ); }

catch ( IOException ioException )


{ displayArea.append( "\nError writing object" ); } }

// utility method called from other threads to manipulate // displayArea in the event-dispatch thread
private void displayMessage( final String messageToDisplay )
{ SwingUtilities.invokeLater (

new Runnable()
{

public void run()


{ displayArea.append( messageToDisplay ); displayArea.setCaretPosition( displayArea.getText().length() ); }

); }

// utility method called from other threads to manipulate // enterField in the event-dispatch thread
private void setTextFieldEditable( final boolean editable )
{

SwingUtilities.invokeLater (

new Runnable()
{

public void run()


{ enterField.setEditable( editable ); }

); }

public static void main( String args[] )


{ Server application = new Server(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); application.runServer(); } } ...

Listing 1: Create a Socket Object try{ ourSocket = new Socket(serverName, 80); }catch(UnknownHostException e){ //..code if the host does not exist }catch(IOException e){ System.out.println(" Unable to open the Socket to "+serverName); } Listing 2: Establish input and output streams. try{ ourInputStream = ourSocket.getInputStream(); ourOutputStream = ourSocket.getOutputStream(); }catch(IOException e){ System.out.println("unable to open streams"); } Listing 3: Closing the socket. try{ ourSocket.close(); }catch(IOException e){ System.out.println("Exception thrown closing the Socket"); } Listing 4 */ public class SocketClient extends Frame implements Runnable{ /* ******* Data Section ******** */ TextField theServer,theFile; TextArea theHTMLCode; Thread thread; Button search, stopSearch; Socket ourSocket; /** * This is the default constructor for this class. Its job is to initialize * the SocketClient object. We construct a Frame Window here. A data entry * panel is created and added "North". Here a user will be able to enter a server

* name and a file to retrieve. If no file name is specified, index.html will be the * default file to search for.*/ public SocketClient(){ setTitle("Socket Client Example"); //Set the frame window title. setLayout(new BorderLayout()); //Set the layout for the window. theServer = new TextField("www.",20); //Create the data entry fields. theFile = new TextField("",20); theHTMLCode = new TextArea("",25,100); theHTMLCode.setEditable(false); //Make the TextArea not editable. Panel pan = new Panel(); //Make a panel to contain the data pan.setLayout(new FlowLayout()); // entry fields and set the layout. pan.add(new Label("http://")); //Add text labels to the panel as pan.add(theServer); // well as the Data Entry Objects. pan.add(new Label("/")); pan.add(theFile); search= new Button("Get the file"); stopSearch= new Button("Stop"); pan.add(search); pan.add(stopSearch);

add("North",pan); //Add the panel North. add("Center",theHTMLCode); //Add the TextArea Center. thread = new Thread(this); //Create a new thread. resize(640,300); //Resize the Window to an appropriate size. show(); //Display the Window. } Listing 5: HandleEvent Method. /** * This is the handleEvent method. We provide code for the events triggered * from a user pressing a button or destroying the window (Exiting the program). * @param Event e * @see event*/ public boolean handleEvent(Event e){ if(e.target == search){ //If the Search Button was pressed, do this. thread.stop(); if(theFile.getText().equals("")){ //If no file was specified theFile.setText("index.html");

// set the file name to index.html. } theHTMLCode.setText("Looking Up Server: "+theServer.getText()); thread = new Thread(this); thread.start(); //This calls the run() method for this. return true; } if(e.target == stopSearch){ //If the Stop Button was pressed, do this. thread.stop(); theHTMLCode.setText("Operation aborted by user"); return true; } if(e.id ==Event.WINDOW_DESTROY){ //If the user wants to exit the program. System.exit(0); //Notice how we do not need to return here. } return super.handleEvent(e); //If we do not handle the event, pass it up the chain. } Listing 6: Run Method /** * This is the run method. It will open a socket connection to a web server and then * get the input and output streams. Then we will simulate the way a web browser * asks the server for a file with the GET statement. After that, we will read the * text data from the web server.*/ public void run(){ //Get the Socket and Streams try{ ourSocket = new Socket(theServer.getText(),80); DataInputStream inStream //Notice how we kill a few birds with one stone. = new DataInputStream(ourSocket.getInputStream()); DataOutputStream outStream //Here too! = new DataOutputStream(ourSocket.getOutputStream());

Listing 7: File Request String. /* Here we construct a file request string. Since we are using * a HTTP server, we need to simulate a file request. We do this * like: GET /filename HTTP/1.0\r\n\r\n * Notice that two ctrl/lf sequences are needed at the end of the request*/ String requestString ="GET /"+ theFile.getText()+" HTTP/1.0\r\n"+ "\r\n"; theHTMLCode.appendText("\n The Request String is:\n"+requestString); outStream.writeBytes(requestString); //Send the Request to the HTTP server outStream.flush(); //Don't forget to flush the stream. theHTMLCode.appendText ("\n ....Asking for file:"+theFile.getText()); //Read the file until EOF. StringBuffer buff = new StringBuffer();

String currLine; while((currLine = inStream.readLine())!=null){ buff.append(currLine + "\n"); } theHTMLCode.setText(buff.toString()); //Place the text into the Text Area. //Close the Socket ourSocket.close(); } catch(Exception e){ /* Since several exceptions can be thrown, We can catch all of them * with the base class for Exceptions.*/ theHTMLCode.setText("Exception with: "+e.getMessage()+"\n"+e.toString()); } } Listing 8: Main Method. /** This is the main method. Program execution begins here */ public static void main(String[] args){ new SocketClient(); } }

import java.net.*; import java.io.*; class clientsock { public static void main(String args[]) throws IOException { System.out.println("sending request to server...."); Socket client=new Socket("127.0.0.1",1235); System.out.println("successfully conneted"); BufferedReader br1=new BufferedReader(new InputStreamReader(System.in)); PrintStream ps=new PrintStream(client.getOutputStream()); BufferedReader br=new BufferedReader(new InputStreamReader(client.getInputStream())); while(true) { System.out.println("input the data u want to send to echo server: "); String s=br1.readLine(); ps.println(s); if(s.equals("exit")) { System.exit(1); } String st=br.readLine(); System.out.println("data returned by the server: "); System.out.println(st); }

} } SERVER SIDE CODE


Code:

import java.net.*; import java.io.*; class serversock { public static void main(String args[]) throws IOException { ServerSocket server=new ServerSocket(1235); System.out.println("waiting for request from client"); Socket client=server.accept(); System.out.println("request accepted"); BufferedReader br=new BufferedReader(new InputStreamReader(client.getInputStream())); while(true) { String st=br.readLine(); if(st.equals("exit")==true) { System.out.println("connection with client is lost...."); System.exit(1); } PrintStream ps=new PrintStream(client.getOutputStream()); ps.println(st); } } }

import java.net.*; import java.io.*; class clie implements Runnable { Thread t; Socket client; clie(Socket client) { this.client=client; t=new Thread(this); t.start(); } public void run() { try{ BufferedReader br=new BufferedReader(new InputStreamReader(client.getInputStream())); while(true) {

String st1=br.readLine(); System.out.println(" "+st1); } } catch(IOException e) { System.out.println(e); } } } class clientsock { public static void main(String args[]) throws IOException { try{ System.out.println("sending request to peer...."); Socket client=new Socket("127.0.0.1",1300); System.out.println("successfully conneted"); clie c=new clie(client); BufferedReader br1=new BufferedReader(new InputStreamReader(System.in)); PrintStream ps=new PrintStream(client.getOutputStream()); while(true) { String s=br1.readLine(); ps.println(s); } } catch(Exception e) { System.out.println(e); } } }

mport java.net.*; import java.io.*; class serv implements Runnable { Thread t; Socket client; serv(Socket client) { this.client=client; t=new Thread(this); t.start(); } public void run() { try { BufferedReader br=new BufferedReader(new InputStreamReader(client.getInputStream()));

while(true) { String st1=br.readLine(); System.out.println("client: "+st1); } } catch(IOException e) { System.out.println(e); } } } class serverchat { public static void main(String args[]) throws IOException { ServerSocket server=new ServerSocket(1300); System.out.println("waiting for request from peer....."); Socket client=server.accept(); serv s=new serv(client); System.out.println("request accepted"); BufferedReader br2=new BufferedReader(new InputStreamReader(System.in)); PrintStream ps2=new PrintStream(client.getOutputStream()); while(true) { String st=br2.readLine(); ps2.println(st); } } }

Вам также может понравиться