mardi 13 novembre 2012

Managing a Cisco Internetwork

1. The Internal Components of a Cisco Router:

The following are the router's components:
- Bootstarp: It will boot the router and then load the IOS.
- POST: Power-On-Self-Test used to check the router's hardware functionality.
- ROM monitor: used for testing and troubleshooting.
- Mini-IOS: called RXBOOT, it's used to load the router IOS into a flash memory.
- RAM: used to hold data (packet, ..).
...

2. Managing Configuration Register:

You can see the current value of the configuration register by using the "show version" command.

2.1. Changing the Configuration Register:

You can change the configuration register value to modify how the router boots and runs. The change can be done using: config-register 0x2101.
The command 'show flash' will show the flash content.


2.2. Recovering Passwords: p 299
The default configuration register value is 0x2102, when loading the router look for configuration stored in NVRAM. To recover a password and ignore the NVRAM content, turn on bit 6. The configuration will become 0x2142.
Here are the main steps to password recovery:
- Iterrupting the Router Boot Sequence: press Ctrl+Break to interrupt the router boot.
- Changing the configuration register: use the 'config-register' command. On Cisco ISR/2600 Series Commands 'confreg 0x2142', Cisco 2500 series, enter 'o/r' followed by the new register value.
- Reloading the Router and Entering Privileged Mode: From the ISR/2600 series type 'I' or 'reset', from a 2500 series type 'I'. When reloading, answer no to enter setup mode.
- Viewing and changing the configuration: copy the startup to the running config file. While you can't view the password since it is encrypted, change the password using the 'enable secret' command.
- Resetting the configuration register and reloading the router: after changing the password, return back the register value to 0x2102.
Finally, save the new configuration to the startup an reload the router.

2.3. Boot System Commands: p 302.
-The 'boot system' command allow you to tell the router which file to boot from flash memory. By default, the router boots the first file found in flash.
-The 'boot system tftp file_name host_addr' command makes your routers boot from TFTP host.
-The 'boot system rom' command loads the mini-IOS from ROM.

3. Backing Up and Restoring the Cisco IOS:

3.1. Verifying Flash Memory:

You can verify the amount of flash memory and the files being stored in flash by using the 'show flash' command.
The 'show version' command shows the actual name of the file that the router is using to run the router.

3.2. Backing Up the Cisco IOS:

To back up the Cisco IOS to a TFTP server, use the 'copy flash tftp' command which will ask you then the server address or name. You have to check the connectivity to the tftp server beforte backing up the IOS.

3.3. Restoring or Upgrading the Cisco Router IOS:

You can download a file from a tftp server to flash by using the 'copy tftp flash' command. Make sure that the file is in the default directory of the tftp server.

3.4. Using the cisco IOS File System (Cisco IFS):

Cisco IFS is a file system that allows you to work with files and directories. The commands you use are dir, copy, more, delete, erase or format, cd and pwd, mkdir and rmdir.
The 'delete' command doesn't free up the space used by the deleted file. To free it up use the command 'squeeze'.
Remember that the IOS is expanded into RAM when the router boots, so the new IOS will not run until you reload the router.

4. Backing Up and Restoring the Cisco Configuration:

4.1. Backing Up the Cisco Router Configuration:

You can use 'copy running-config tftp' or 'copy startup-config tftp' to back up the router configuration that's currently in DRAM or in NVRAM.

4.2. Copying the Current Configuration to NVRAM:

You can use startup-config as a back up, and the current config will be reloaded as the router reboot.

4.3. Copying the Configuration to a TFTP Server: p 317
You can make a back up of the running-config to a tftp server using 'copy running-config tftp'. To restore the configuration use 'copy tftp running-config' or 'copy tftp startup-config'.

4.4. Erasing the Configuration:

To delete the stratup-config file use the command 'erase startup-config'. If you relaod without saving changes, you'll be directed to setup mode.

5. Using Cisco Discovery Protocol (CDP):

It's a proprietary protocol designed to collect information about locally attched and remote devices.

5.1. Getting CDP Timers and Holdtime Information:

The 'sh cdp' command gives you information about two global parameters:
- CDP timer is how often CDP packets are transmitted out all active interfaces;
- CDP holdtime is the amount of time that the device will hold packets received from neighbor devices.
The commands 'cdp holdtime' and 'cdp timer' allows to configure the CDP's.
Use 'no cdp run' to turn off cdp, 'no cdp enable' and 'cdp enable' to turn off or on for an interface.

5.2. Gathering Neighbor Information:

The 'show cdp neighbor' command delivers information about directely connected devices. CDP packet aren't passed through a Cisco switch.
The 'show cdp neighbors detail' can be run on a router or a switch, it displays detailed information about each directly connected device.
The 'show cdp entry *' command displays the same information as the previous command, but has two options. 'show cdp entry * protocols' display only the ip address of the directly connected devices, 'show cdp entry * version' show only the IOS version.

5.3. Gathering Interface Traffic Information:

The 'show cdp traffic' command displays information about interface traffic, including the number of CDP packets sent and received and errors with CDP.

5.4. Gathering Port and Interface Information:

The 'show cdp interface' gives you the CDP status on router interfaces or switch ports. You can turn off the cdp on a per-interface basis with 'no cdp enable' from the interface configuration mode. You enable a port with 'cdp enable'.

5.5. Documenting a Network Topology Using CDP:

You have a router with a four interfaces, two FastEthernet and two Serial. First, determine the IP addresses of each interface by using the 'show running-config'.
Next, you need to determine the type of device on the others end of each of these interfaces by using 'show cdp neighbors'. Now you know about all the IP addresses of the router plus the types of routers connected to each of its interfaces.
And so you can reveal the network topology. We could've also used the 'show cdp neighbors detail' to view the neighbor's IP addresses.

6. Using Telnet: p 336
On a cisco router, when typing an IP address it assume that you want to telnet to the device. The VTY password is the user-mode password, not enable-mode's one.
To allow console messages to be sent to your Telnet session, use the 'terminal monitor' command.

6.1. Telnetting into Multiple Devices Simultaneously:

You can end a telnet session by typing 'exit', to return to the original router console without closing the telnet session press 'Ctrl+Shift+6', then X.

6.2. Checking Telnet Connections:

To see the connections made from your router to a remote device use 'show sessions'. Youis last session will be prefixed by an asterisk. You can return to a session by typing the number of the connection.

6.3. Checking Telnet Users:

You can list all active consoles and VTY ports in use on your router with 'show users'. In the output, 'con' represent local console. 'vty' has an IP address connected to the local device.

6.4. Closing Telnet Sessions:

To end a telnet session enter 'exit' or 'disconnect' (from a local device and specifying the sessin number). To end a session of a device attached to the local device through Telnet, first check if any devices are telnetted into your router by 'show users', then to clear the connection, use 'clear line #' (# is port number).

7. Resolving Hostnames:

7.1. Building a Host Table:

A host table provides name resolution only on the router that it was built upon. It can be built by 'ip host  host_name tcp_port_number ip_address'. You can assign up to eight IP addresses to a hostname. 'show hosts' to view the table.
If you want to remove a hostname from the table use 'no ip host' command.

7.2. Using DNS to Resolve Names:

When typing anything that can't be understood by the device, it try to resolve it using DNS, you can prevent a time-consuming DNS lookup by using 'no ip domain-lookup'. If you have a DNS server, the following steps make DNS  
name resolution work:
- 'ip domain lookup' is turned on by default;
- 'ip name-server' sets the up to six IP addresses of the DNS server.
- 'ip domain-name' (optional). It appends the domain name to the hostname you type in, you must have a full DNS name like domain.com .

8. Checking Network Connectivity and Troubleshooting:

8.1. Using the ping Command:

Type 'ping ?' to see the different protocols that you can use with the ping program. The ping can be used in user and privileged mode, but not in configuration mode.

8.2. Using the traceroute (trace) Command

It shows the path a packet takes to get to a remote device. It show you which router in the path to an unreachable network host should be examined more closely for the cause of the network's failure.

8.3. Debugging (p 349)
Debug command is used to display information about various router operations and the related traffic generated or received by the router. Type 'debug ?' to see all options. To disable debugging 'no debug all' or 'undebug all'.

8.4. Using the show processes Command:

The 'show processes' (or 'show processes cpu') to determine a given rouuter's CPU utilization. It will give a list of active processes along with their corresponding process ID, priority, scheduler test (status), CPU time used, number of times invoked.

Introduction to TCP/IP

1. The Process/Applicationn Layer Protocols:

1.1. Simple Mail Transfert Protocol (SMTP):

SMTP is used to send mail, POP3 to receive mail.

1.2. Line Printer Daemon (LPD)

It is designed for printer sharing. The LPD, along with the Line Printer (LPR) program, allows print job to be spooled and sent to the network's printer using TCP/IP.

1.3. X Window:

It defines a protocol for writing client/server application based on a graphical user interface (GUI). Allow a program (client) to run on one computer and have it display through a window server on another computer.

1.4. Simple Network Management Protocol (SNMP)

It collects and manipulates valuables network information. It gathers data by polling the devices on the network from a management station each intervals. When all is well, SNMP receives something called a baseline -- a report delimiting the operational traits of a healthy network. Agent (SNMP stand as a watchdog over the network) send trap to management station.

1.5. Domain Name Service (DNS):

DNS is used to resolve a Fully Qualified Domain Name (FQDN); this one is a hierarchy that can logically locate a system based on its domain identifier.
If you want to resolve the device toad, you must enter the FQDN, or let your router adding the suffix by configuring it such: ip domain-name lammle.com to append this suffix to all resolvation requests.

1.6. Dynamic Host Configuration Protocol (DHCP)/Bootstrap Protocol (BootP):

BootP assigns an IP address to a host but the host's hardware address must be entered manually in a BootP table. DHCP is a dynamic BootP. BootP is also used send an operation system that a host can boot from. DHCP can't do that.
When a host is requesting an IP address by sending a DHCP Discover message, the DHCP server (which can be any device) send the following information:
IP address, Subnet mask, domain name, default gateway (routers), DNS, WINS information.


2. The Host-to-Host Layer Protocols:


2.1. Transmission Control Protocol (TCP) (p 116)
TCP is full-duplex, connection-oriented, reliable, and accurate protocol, establish error checking.

2.1.1. TCP Segment Format:

The TCP header is 20 bytes long (up to 24 bytes with options):
 - Source port: 2 bytes for port number of the sender application.
 - Destination port: port number of the destinated application.
 - Sequence number: A number used by TCP that puts data back in the correct order.
 - Acknowledgment number: The next TCP octet expected.
 - Header length: indicates where the data begins.
 - Reserved: always set to zero.
 - Code bits: (6-bits), control functions used to set up and terminate a session.
 - Window: The window size the sender is willing to accept, in octets.
 - Checksum: The CRC checks the header and data fields.
 - Urgent: A valid field only if the Urgent pointer is put in the code bits. The value indicates the offset from the current sequence number, in octets, where the first segment of non-urgent data begins.
 - Options: May be 0 or a multiple of 32 bits.
 - Data:

2.2. User Datagram Protocol (UDP)

2.2.1. TCP vs UDP:

The cost in overhead to establish, maintain, an dclose a TCP connection would reduce efficient network. Use UDP instead of TCP when reliability is already handled at the Process/Application layer.
UDP is a connectionless protocol, it doesn't create a virtual circuit, nor does it contact the destination before delivering information.
2.2.2 UDP Segment Format:
- Source port;
- Destination port;
- Length of UDP header and data;
- Checksum of both UDP header and data;
- Data.

2.3. Key Concepts of Host-to-Host Protocols (TCP vs UDP, p 120)
2.4 Port Numbers (p 121)
The different port numbers that can be used are explained next:
- Numbers below 1024 are considered well-know port numbers and are defined in RFC 3232.
- Numbers 1024 and above are used by the upper layers to set up sessions with other hosts and by TCP.
2.4.1. TCP Session: Source port
The source make up a port number ro differentiate between sessions with different hosts. How would a server know where information is coming from if it didn't have a different number from a sending host. It's easy to imagine the receiving host getting throughly confused if all the hosts used the same source port number to get to FTP.

2.4.2. TCP Session: Destination Port

Sometimes when looking to an analyzer, we can see that only the source port is above 1024 and the destination port is a well-known port.

2.4.3. TCP Session: Syn Packet Acknowledgment

TCP protocols                      UDP Protocols
TELNET (23)                             SNMP  (161)
SMTP    (25)                             DNS     (53)
HTTP    (80)
FTP       (21)
DNS      (53)
HTTPS  (443)

3. The Internet Layer' Protocols:

IP provide routing fnctionalities, and a single network interface to upper layers (no need to build different application's version for evry network Ethernet, Token Finder,..).

3.1. Internet Protocol (IP): (p 125)

Internet Protocol (IP)  essentially is the Internet layer. The other protocols found here merely exist to support it. The following fileds make up the IP header:
- Version: IP version number;
- Header length: HLEN in 32-bits word;
- Priority and Type of Service: Type of service tells how the datagram should be handled. The first 3-bits are for priority;
- Total length: packet length including header and data;
- Identification: Unique IP-packet value;
- Flags: specifies whether fragmentation should occur;
- Fragment offset: provides fragmentation and reassembly if the packet is too large to put in a frame;
- Time to Live: This stopes IP packets from continuously circling the network looking for a home;
- Protocol: Port of upper-layer protocol (TCP is port 6, UDP is port 17 [hex]). Also supports Network layer protocols, like ARP and ICMP.
- Header checksum: CRC of the header;
- Source IP address: 32-bits IP address of sending station;
- Destination IP address: 32-bits of the destinated station;
- Options: Used for network testing, debugging, security, and more;
- Data: upper-layer data.

3.2. Internet Control Message protocol (ICMP): (p 128)
ICMP packets have the following characteristics:
- They can provide hosts with information about network problems;
- They are encapsulated within IP datagrams.
The following are some commen events and messages that ICMP relates to:
3.2.1. Destination Unreachable:
If a router can't send an packet, it uses ICMP to send back a message to the sender, advising it of the situation.
3.2.2. Buffer Full:
If a router's memory is full, it use it to send out this message.
3.2.3. Hops:
Uesed to inform the sender that its packet have been dropped by the last router after the hop packet get its limit.
3.2.4. Ping (Packet Internet Groper):
Ping uses ICMP echo request and reply messages to check the logical and physical connectivity of machines.
3.2.5. Traceroute:
Using ICMP time-outs to discover the path a packet takes as it traverses an internetwork.

3.3. Address Resolution Protocol (ARP):

It finds the hardware address of a host from a known IP address. ARP interogates the local network by sending out a broadcast asking the machine with the specified IP address to reply with its hardware address.

3.4. Reverse Address Resolution Protocol (RARP):

If a host is looking to its IP address, it send a RARP request to a RARP server with its MAC address, the server will respond with the answer and the identity crisis is over.

3.5. Proxy Address Resolution Protocol (Proxy ARP):

When a router turns down, the host won't immediately start sending ro another one -- it must be configurate. Proxy ARP can help machines on a subnet reach remote subnets without configuring routing. Proxy ARP is added as a service to the router, and is enabled by default. Using it imply host to have a larger ARP table in order to handle all the IP-to-MAC address mappings. Disable it if you don't have to use it.

4. IP Addressing (p 133)

4.1. The Hierarchical IP Addressing Scheme:

4.1.1. Network Addressing: (p 135)
Class A: Network .    Host    .    Host    . Host
Class B: Network . Network .    Host    . Host
Class B: Network . Network . Network . Host
Class D: Multicast
Class E: Research

4.1.1.1. Network Address Range: Class A
The first byte in a Class A must always be 0. It is between 0 and 127.
4.1.1.2. Network Address Range: Class B
In a Class B, the first bit of the first byte is 1, the second bit must always been 0.
Class B addresses are between 128 and 191.
4.1.1.3. Network Address Range: Class C
The first 2 bits of the first byte are set to 1, the third is always 0.
The range of addresses is from 192 to 223.
4.1.1.4. Network Address Range: Class D and E
you don't need them, Class D (224-239) is for multicast addresses.
Class E (240-255) is form scientific purposes.
4.1.1.5. Network Addresses: Special Purpose
- Network address of all 0s: Interpreted to mean "this network or segment".
- Network address of all 1s: Interpreted to mean "all networks".
- Network 127.0.0.1: reserved to loop back tests.
- Node address of all 0s: Interpreted to mean "network address" or any host on specified network.
- Node address of all 1s: Interpreted to mean "all nodes" on the specified network, ex: 128.2.255.255.
- Entire IP address set to all 0s: Used by Cisco routers to designate the default route.
- Entire IP address set to all 1s: Broadcast to all nodes on the current network.

Class A Addresses (p 137)
The network address 0000 0000 is reserved to designate the default route.
The address 127 is reserved for diagnostics.

4.1.2. Private IP Addresses:

Private IP addresses can be used on a private network, but they're not routable through the Internet. By using private IP addresses, users need a tiny group of bona fide IP addresses to connect their network to Internet. To accomplish that, they need Network Address Translation (NAT). Which convert a private IP address for use on the Internet.
Class A private address range is 10.0.0.0 through 10.255.255.255 .
Class B private address range is 172.16.0.0 through 172.31.255.255 .
Class C private address range is 192.168.0.0 through 192.168.255.255 .

5. Broadcast Addresses (141)
There is 4 type:
- Layer 2 broadcasts  : These are sent to all nodes on a LAN. hardware broadcast has the address FF.FF.FF.FF.FF.FF.
- Broadcasts (layer 3): These are sent to all nodes on the network. Broadcast message are meant to reach all hosts on a broadcast domain. (Network Broadcast).
- Unicast                    : These are sent to a single destination hosts.
- Multicast                 : These are packets sent from a single source and transmitted to many devices on different networks.

Unicast it's a broadcast that goes from 255.255.255.255 to an actual destination IP address, it's directed to a specific host, like a DHCP client request.

Multicast does allow point-to-multipoint communication. It works by sending messages to IP multicast group addresses, routers then forward copies out every interface that has hosts 'subscribed' to that group address. Like EIGRP packets.
The range of multicast addresses starts with 224.0.0.0 and goes through 239.255.255.255 . This range falls within IP Class D.

SnapMeme

The application allows users to create mémé from a snapshot of a video. Dailymotion API are used to search for videos (according to user keywords) and disply the chosen video to user. Then at any moment the user can take a snapshot of the current displayed frame from the video, add text on it to share the resulting drawing (also called Mémé) on social networks (e.g. Twitter).

Démo
 
A snapshot of the posted message on twitter

More details about the event can be found here.

TerroirCaisse

More information about the event can be found here at iphon.fr (in french).
The used data was provided by data.visitprovence.com. The application source code can be found at github.

lundi 29 octobre 2012

Test the Web Forward

During 2 days (26 and 27 of October, 2012), Test The Web Forward was held in Paris where people come from different countries mostlty France and US (San Fransisco) but even Australia to write test for the latest W3C specifications (HTML5, CSS3, Apache Cordova, etc.).

Vincent Hardy (Adobe) introduced the event and welcomed the attendee.
Then came Robin Berjon (W3C) to talk about how to read a spect in a way to write a test for it: read it forward and backward!
Spec have to deal with complex things (ex. the red button implementation may differs in details from one browser to another: form, shape)
In the spec look for the conformance requirement for details
  • The "product" what it is applied to (ex. uers agrnt, the browser) -> what you want to test (product)
  • Strinctness level (must, should: option, may)
  • Prerequisites
  • Behabiour of the product (e.g. ignore the element)
  • Defined terms: tell you what is it mean (e.g. absent, empty string, ignore)
Finding definitins (repeated) are close to the begining

Then, Rebecca Hauck (Adobe) talked about reference tests (reftest) and how to write one.
Then, James Graham (Opera) talked about how to use testharness.js to writing javascript tests for W3C specifications. Here is some examples from the talk:
  • Sync test: example with local storage getItem() that returns the value associated with a key, or null if none
  • Async test: clear storage example when clearStorage() called from a window than an event is fired in an iframe contained in the same document
Finally, Elika J. Etemad also known with fantasai (Mozilla) How to file a good bug report in bugzilla or any other bug reporting system.

After this session, lightning talks started where experts presented some W3C specifications they would like people to join to write test for them. The goal is tests inheritance as they can be writting befroe code as test were writting for W3C spec.

Apache Cordova (Michael Brooks from Adobe)
Apache Cordova (also known as PhoneGap) implements W3C API to map javascript code to native methods. The task was to convert jasmine test it to testharness.js (they were around 200 tests).

IndexedDB (Odin Hørthe Omdal from Opera)
Under active development, Implemented in many browsers, needs tests (333 so far).

CSS3 backgrounds (Microsoft)

W3C HTML5 Testing Task Force
A groud writting tests for testing HMTL5 spec, has a CVS.
Why? used by user agent implementers (tv, stereo, , refrigirator).
Read wiki and presentation.

WebRTC aim is to be able to do video/audio communication on the web + P2P communication between two browser.
  • GetUserMedia: allows a script to get access to microphone, first ask user consent.
  • PeerConnection: helps you send video data over internet to : quality of video based on available for the browser.
  • DataChannel: send banch of data between browsers.
More resources can be found here:

jeudi 4 octobre 2012

Read/Write NFC tag in Android

Android & NFC howto

When a NFC tag is discovered, the system checks if the foreground application has registered to such an Intent with a call to enableForegroundDispatch(). If not, it checks whether any other applications has registered for the NDEF_DISCOVERED intent. If an application want to register for events related to a tag of a specific technology (e.g. classic MiFare tags) then it should register to the TECH_DISCOVERED intent.
The following diagram explains in details how an event related to reading a tag is handled:

Read NFC tag in Android

Declare in the manifest a specific Activity to receive an Intent when a NFC tag is read by the device:
<activity android:name=".NfcReaderActivity" android:label="NfcReaderActivity">
    <intent-filter>
     <action android:name="android.nfc.action.TAG_DISCOVERED"/>
     <category android:name="android.intent.category.DEFAULT"/>
    </intent-filter>
</activity>

To register the foreground Activity for tag reading events, add following lines to onResume() method:
@Override
protected onResume() {
  PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, this.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
  mAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
} 

In the onNewIntent(Intent)to read the tag after receiving a ACTION_TAG_DISCOVERED intent :
protected void onNewIntent(Intent intent) {
  String action = intent.getAction();
  if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)){
    Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
    NdefMessage[] messages;
    if (rawMsgs != null) {
      messages = new NdefMessage[rawMsgs.length];
      for (int i = 0; i < rawMsgs.length; i++) {
        messages[i] = (NdefMessage) rawMsgs[i];     
        // To get a NdefRecord and its different properties from a NdefMesssage   
     NdefRecord record = messages[i].getRecords()[i];
     byte[] id = record.getId();
     short tnf = record.getTnf();
     byte[] type = record.getType();
     String message = getTextData(record.getPayload());
      }
    }
  }
}

This is how to read the content tag of type text RTD_TEXT
// Decoding a payload containing text
private String getTextData(byte[] payload) {
  if(payload == null) 
    return null;
  try {
    String encoding = ((payload[0] & 0200) == 0) ? "UTF-8" : "UTF-16";
    int langageCodeLength = payload[0] & 0077;
    return new String(payload, langageCodeLength + 1, payload.length - langageCodeLength - 1, encoding);     
  } catch(Exception e) {
    e.printStackTrace();
  }
  return null;
}

Write NFC tag in Android

In the manifest:
<uses-permission android:name="android.permission.NFC" />
<uses-feature android:name="android.hardware.nfc" android:required="true" />
in onCreate() get the NfcAdapter:
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
The data part of a TAG is a NdefMessage of multiple NdefRecord this is how to encode a text into a payload:
// Encoding a text into a tag payload 
NdefRecord createRecord(String message) {
  byte[] langBytes = Locale.ENGLISH.getLanguage().getBytes(Charset.forName("US-ASCII"));
  byte[] textBytes = message.getBytes(Charset.forName("UTF-8"));
  char status = (char) (langBytes.length);
  byte[] data = new byte[1 + langBytes.length + textBytes.length];
  data[0] = (byte) status;
  System.arraycopy(langBytes, 0, data, 1, langBytes.length);
  System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length);
  return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], data);
}
// Create a message from a record
NdefMessage createMessage(NdefRecord record) {
  NdefRecord[] records = new NdefRecord[1];
  records[0] = record;
  NdefMessage message = new NdefMessage(records);
  return message;
}
To enable/disable sending a message each time a tag is read
@Override
protected void onPause() {
  super.onPause();
  nfcAdapter.disableForegroundNdefPush(this);
}
@Override
protected void onResume() {
  super.onResume();
  NdefRecord record = creerRecord("this is a message");
  NdefMessage message = creerMessage(record);
  nfcAdapter.enableForegroundNdefPush(this, message);
}
If there is no tag, we can simulate a tag been read by sending the corresponding intent, this is how:
final Intent intent = new Intent(NfcAdapter.ACTION_TAG_DISCOVERED);
NdefMessage[] messages = new NdefMessage[1];
messages[0] = createMessage(createRecord("Simulating a tag reception"));
intent.putExtra(NfcAdapter.EXTRA_NDEF_MESSAGES, messages);
startActivity(intent); 

Reference Programming Android, chapter 16: Sensors, NFC, Speech, Gestures, and Accessibility.